java - JPA/Hibernate 级联持久不起作用

标签 java spring hibernate jpa

我在将持久操作级联到子级时遇到问题。

我有一个父级和一个子级。当我使用 Spring-Data Repository 保存父级和一个子级时,子级的值全部为 null 或 0。

如果我将 CascadeType.ALL 添加到 OneToMany-Annotation 中,我会收到此错误: “同一实体的多个表示正在合并”

@Entity
@Getter
@Setter
public class TestParent {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "parent", cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE}, orphanRemoval = true)
    private List<TestChild> children;
}

@Entity
@Getter
@Setter
public class TestChild {
    @Id
    @GeneratedValue
    private Long id;

    private int value;

    @ManyToOne
    private TestParent parent;
}

以下是测试保存对象是否有效的代码:

@Test
@Transactional
public void test123(){
    TestParent parent = new TestParent();
    parent = testRepo.save(parent);

    TestChild child1 = new TestChild();
    child1.setValue(3);
    child1.setParent(parent);
    parent.setChildren(new ArrayList<>());
    parent.getChildren().add(child1);

    parent = testRepo.save(parent);

    assertThat(parent.getChildren().size()).isNotZero();
    assertThat(parent.getChildren().get(0).getValue()).isEqualTo(3);
}

所以我的方法是修复级联 Persist 而不添加cascadeType Merge。有什么提示我做错了什么吗?

最佳答案

第一Hibernate User Guide如果您想了解有关将实体映射到数据库的知识,这是一个很好的资源。

我检查了您的示例,它可以在我的机器(TM)上运行,并具有以下存储库声明:

public interface PersonRepository extends CrudRepository<HibernateProxyDemoApplication.TestParent, Long> {  }

和 Spring Boot 应用程序:

@SpringBootApplication
@EnableJpaRepositories // just to make sure
public class HibernateProxyDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(HibernateProxyDemoApplication.class, args);
    }
...
}

pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

我只能建议你先删除Lombok注解(@Getter/@Setter)并手动编写getter/setter,然后看看你的程序可能有什么问题。

PS。它也适用于级联 ALL

关于java - JPA/Hibernate 级联持久不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45333941/

相关文章:

java - Maven 配置文件和 Artifact 版本

java - 按值集的大小对 HashMap 进行排序

java - Spring boot @ComponentScan 与 @Import

java - Hibernate 4 EntityManager CriteriaBuilder sortby 嵌套属性

java - Spring MVC : Testing with selenium failing with commons-io not found(it exists)

java - 将 hibernate 实体转换为 JSON : oblectId instead of whole object

java - 如何在 JPA 中构建插入查询

mysql - 选择具有最高日期的行

java - aspose removeChild 后,run 原来的字体变了

java - 使用 arraylist 的最大非负子数组