我有两个 A 类和 B 类
class A{
@ManyToOne(cascade=CascadeType.ALL)
B b;
// other stuff
}
B类
class B{
@Id
@Column(unique = true, nullable = false)
private Integer id;
// other stuff
}
每当创建 A 的新对象时,如果对象 B 尚不存在,我想创建该对象。但是,如果它已经存在,那么我不想创建它。在本例中,我只需要 A 表中已存在的 B 对象的引用。现在,当我尝试这样做时,我遇到了这个异常
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '10' for key 'PRIMARY'
这似乎是一个标准任务,但我似乎在 stackoverflow 等上找不到任何解决方案。有人可以帮忙吗?谢谢!!
编辑:为了进行保存,我使用 Sring JPA 存储库。我有 A 和 B 的存储库接口(interface),最终扩展 CrudReposioty
并使用其保存功能。以下是 org.springframework.data.repository.CrudRepository
中的函数
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity
* @return the saved entity
*/
<S extends T> S save(S entity);
最佳答案
在将对象A插入数据库之前,需要设置对象B的id。在这种情况下,如果B不存在,B将被插入到数据库中。
关于java - Hibernate:CascadeType.ALL 应该尝试创建该对象(如果该对象尚不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45185975/