java - Hibernate:CascadeType.ALL 应该尝试创建该对象(如果该对象尚不存在)

标签 java mysql hibernate

我有两个 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/

相关文章:

java - 无法通过 Java Maleorang 的 MailChimp API 3.0 包装器获取数据 - 404 错误

MySQL - WHERE IN CLAUSE 正则表达式匹配电话号码

php - MySQL中的Strtotime查询[基本PHP页面]

java - 使用 Asprise 和 Java 对 PDF 进行 OCR

java - 覆盖扩展接口(interface)中的返回类型 - 坏主意?

java - 使用 saveOrUpdate hibernate : Random Exceptions and record not updated during session flush,

java - 在 spring data JPA 中更新和返回数据

java - Spring MVC + hibernate : a form with checkboxes for @manytomany relationship

java - java中如何动态设置一个对象?

php - 超链接 SQL 查询的第一个结果