gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:29:53 24 4
gpt4 key购买 nike

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

我有一个父级和一个子级。当我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com