2017-07-19 132 views
0

我有两个类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); 
+0

添加执行保存/更新并导致excetpion的方法 –

+0

您可以使B中的Id成为生成的值吗? –

+0

@MaciejKowalski这个id将会被提供,因此不会产生任何帮助。我想这与弹簧数据JPA有关,然后休眠 – varunkr

回答

2

你需要插入对象的数据库之前设置对象B的ID的功能。在这种情况下,如果B不存在,B将被插入到数据库中。

+0

我确实设置了ID,并且您提到的情况正常工作。它当B存在于db中时会抛出异常 – varunkr

+0

什么是异常? –