使用关系保存失败:无法处理托管/反向引用

Saving with relation fails: Cannot handle managed/back reference

提问人:Yozhef Handraburh 提问时间:7/20/2023 最后编辑:Yozhef Handraburh 更新时间:7/21/2023 访问量:51

问:

我有一个测试,其中包括 TestBook,其中包括 Block。当我尝试更新我的测试时,收到此错误:

2023-07-20T17:58:19.021+02:00 DEBUG 88644 --- [nio-8082-exec-5] o.s.security.web.FilterChainProxy        : Secured PUT /update-test/1

2023-07-20T17:58:19.069+02:00  WARN 88644 --- [nio-8082-exec-5] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class myproject.model.Test]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.List<myproject.model.TestBlock>`) not compatible with managed type (myprojectngulata.model.TestBlock)

2023-07-20T17:58:19.101+02:00  WARN 88644 --- [nio-8082-exec-5] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class myproject.model.Test]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.List<myproject.model.TestBlock>`) not compatible with managed type (myproject.model.TestBlock)

2023-07-20T17:58:19.106+02:00 TRACE 88644 --- [nio-8082-exec-5] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure]

2023-07-20T17:58:19.106+02:00  WARN 88644 --- [nio-8082-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/json;charset=UTF-8' is not supported]

2023-07-20T17:58:19.110+02:00 TRACE 88644 --- [nio-8082-exec-5] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter@47aa7caa, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@ad79c3, org.springframework.security.web.context.SecurityContextHolderFilter@209137bb, org.springframework.security.web.header.HeaderWriterFilter@42023771, org.springframework.web.filter.CorsFilter@3bee9a82, org.springframework.security.web.csrf.CsrfFilter@50583645, org.springframework.security.web.authentication.logout.LogoutFilter@2e9f3a2f, org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter@7ef5fb0, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@403fb6f3, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@3cafb7f5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@8174188, org.springframework.security.web.session.SessionManagementFilter@53361e2c, org.springframework.security.web.access.ExceptionTranslationFilter@2a8c3c4a, org.springframework.security.web.access.intercept.AuthorizationFilter@8e673df]] (1/1)

这是我的模特

测试

import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;

import jakarta.persistence.*;

@Entity
public class Test {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;
    private String description;
    private Integer difficulty;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "direction_id")
    private Directions direction;

    @JsonManagedReference
    @OneToMany(mappedBy = "test", cascade = CascadeType.ALL)
    private List<TestBlock> testBlock;

    @Column(name = "direction_id", insertable = false, updatable = false)
    private Integer direction_id;

    public Test() {

    }

    public Test(String name, String description, Integer difficulty, Integer direction_id) {
        this.name = name;
        this.description = description;
        this.difficulty = difficulty;
        this.direction_id = direction_id;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getDifficulty() {
        return difficulty;
    }

    public void setDifficulty(Integer difficulty) {
        this.difficulty = difficulty;
    }

    public Directions getDirection() {
        return direction;
    }

    public void setDirection(Directions direction) {
        this.direction = direction;
    }

    public Integer getDirection_id() {
        return direction_id;
    }

    public void setDirection_id(Integer direction_id) {
        this.direction_id = direction_id;
    }
}

测试块

import jakarta.persistence.*;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity
public class TestBlock {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "test_id")
    @JsonBackReference
    private Test test;

    @ManyToOne
    @JsonManagedReference
    private Block block;

    private Integer quantityQuestions;

    public TestBlock() {
    }

    public TestBlock(Test test, Block block, Integer quantityQuestions) {
        this.test = test;
        this.block = block;
        this.quantityQuestions = quantityQuestions;
    }

    public Integer getId() {
        return id;
    }

    public Test getTest() {
        return test;
    }

    public void setTest(Test test) {
        this.test = test;
    }

    public Block getBlock() {
        return block;
    }

    public void setBlock(Block block) {
        this.block = block;
    }

    public Integer getQuantityQuestions() {
        return quantityQuestions;
    }

    public void setQuantityQuestions(Integer quantityQuestions) {
        this.quantityQuestions = quantityQuestions;
    }

}

import jakarta.persistence.*;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity
public class Block {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String title;
    private String description;

    @JsonManagedReference
    @OneToMany(mappedBy = "block", cascade = CascadeType.ALL)
    private List<Question> questions;

    @JsonBackReference
    @OneToMany(mappedBy = "block", cascade = CascadeType.ALL)
    private List<TestBlock> testBlock;

    public Block() {
    }

    public Block(String title, String description) {
        this.title = title;
        this.description = description;
    }

    public Integer getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }

}

和我的updateMethod适用于任何情况

    public Test updateTest(Integer id, Test updatedTest) {
            Test currentTest = testRepository.findById(id).orElse(null);
            if (currentTest == null) {
                return null;
            }
    
            currentTest.setName(updatedTest.getName());
            currentTest.setDescription(updatedTest.getDescription());
            currentTest.setDifficulty(updatedTest.getDifficulty());
            currentTest.setDirection_id(updatedTest.getDirection_id());
    
            Optional<Directions> directionsOptional = directionsRepository.findById(updatedTest.getDirection_id());
            if (directionsOptional.isPresent()) {
                Directions direction = directionsOptional.get();
                currentTest.setDirection(direction);
            }
    
            testRepository.save(currentTest);
            return currentTest;
        }

最近,我在 Test 和 TestBlock 之间添加了连接,以便能够从 Test 获取所有需要的 Blocks 数据,而不是使用额外的获取。

我在网上冲浪时看到了类似的问题,但我能找到的解决方案就是注释 - @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property=“id”),但它对我一点帮助都没有。

Java Spring Hibernate 一对 多对一

评论

0赞 Community 7/21/2023
请修剪您的代码,以便更轻松地找到您的问题。请遵循这些准则,以创建最小的可重现示例

答: 暂无答案