我有两个类A和B,使得休眠:CascadeType.ALL应该尝试创建对象,如果它不存在
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,如果它不存在。但是,如果它已经存在,那么我不想创建它。在这种情况下,我只想在已经存在的B对象的A表中引用。现在,当我尝试这样做
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '10' for key 'PRIMARY'
这似乎是一个标准的任务,但我似乎无法找到关于计算器等。可有人请帮助解决任何我得到这个例外。谢谢 !!
编辑:为了保存,我使用了Sring JPA存储库。我有A和B的存储库接口,最终扩展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);
添加执行保存/更新并导致excetpion的方法 –
您可以使B中的Id成为生成的值吗? –
@MaciejKowalski这个id将会被提供,因此不会产生任何帮助。我想这与弹簧数据JPA有关,然后休眠 – varunkr