java – Spring Data Repository:传递给persist的分离实体
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring Data Repository:传递给persist的分离实体,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2171字,纯文字阅读大概需要4分钟。
内容图文
![java – Spring Data Repository:传递给persist的分离实体](/upload/InfoBanner/zyjiaocheng/779/5bd6795883764316aec3cbf207316ce0.jpg)
配置文件对象具有任务列表.
保存新配置文件时,任务列表也应与数据库同步(插入或更新).问题是profile-repository的save() – 方法只允许一个或另一个方法依赖于属性上方的级联属性(CascadeType.PERSIST或MERGE).
Profile类
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class AbstractProfile implements Profile {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private List<Task> tasks;
..
JUnit-Test类
public class ProfileTaskRepositoryTest {
@Autowired
private ProfileRepository profileRepo; //extends JpaRepository
@Autowired
private TaskRepository taskRepo; //extends JpaRepository
@Test // ->this test passes
public void testCreateProfileWithNewTask() {
//profileData and taskData hold dummy data. They return new objects
AbstractProfile interview = profileData.createITInterviewProfile();
Task questionTask = taskData.createInterviewQuestionTask();
//add new task to profile and save
interview.addTask(questionTask);
profileRepo.save(interview);
//task repository confirms the insertion
assertTrue(taskRepo.count() == 1);
}
@Test // ->this test fails
public void testCreateProfileWithExistingTask() {
//first create task and save in DB
Task questionTask = taskData.createInterviewQuestionTask(); // transient obj
taskRepo.save(questionTask); // questionTask becomes detached
// then create a new profile and add the existing task.
// the problem is the existing task is now detached)
AbstractProfile interview = profileData.createITInterviewProfile();
interview.addTask(questionTask);
profileRepo.save(interview); // !!! this throws an exception
}
我想当taskRepo将它保存在DB中然后关闭会话时,questionTask-object会被分离.
例外:
org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: detached entity passed to persist: *.Task; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: *.Task
...
profileRepo.save()应该能够处理任务列表的插入和更新.有没有一种优雅的方法来解决这个问题?
解决方法:
您应该在测试类上放置@Transactional属性以避免异常.
@Transactional
@TransactionConfiguration
public class ProfileTaskRepositoryTest {
}
希望这可以帮助.
内容总结
以上是互联网集市为您收集整理的java – Spring Data Repository:传递给persist的分离实体全部内容,希望文章能够帮你解决java – Spring Data Repository:传递给persist的分离实体所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。