作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在将持久操作级联到子级时遇到问题。
我有一个父级和一个子级。当我使用 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/
我是一名优秀的程序员,十分优秀!