【问题标题】:DataIntegrityViolationException: could not execute statement. When perform save operation for @OneToOne JPA mappingDataIntegrityViolationException:无法执行语句。为@OneToOne JPA 映射执行保存操作时
【发布时间】:2020-11-17 14:45:22
【问题描述】:

我收到“org.springframework.dao.DataIntegrityViolationException:无法执行语句;SQL [n/a];约束 [null];嵌套异常是 org.hibernate.exception.ConstraintViolationException:无法执行语句”异常同时将对象保存到存储库中。

要求:计划只有一个定价对象,所以我添加了@OneToOne 映射。下面是预期的表结构。

Plan table
-------------
id | planname

Cpricing table
----------
id | cdata | plan_id(fk)
    

我在实体类中有以下代码更改:

Plan {
    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pl")//created one to one mapping between the cPricing
    private CPricing priceInfo;
}
    
CPricing {       
    @OneToOne(fetch = FetchType.LAZY) //created one to one mapping between the plan
    @JoinColumn(name = "plan_id", nullable = false, unique = true)
    private Plan pl;
}

尝试保存包含 CPricing 对象的 Plan 对象时引发异常。

映射是否正确?

【问题讨论】:

  • 能否请您分享整个堆栈跟踪,您的实体类中的一个字段似乎是 null 导致问题持续存在。

标签: java database hibernate spring-data-jpa hibernate-mapping


【解决方案1】:

这里你把@JoinColumn放在CPricing一侧,所以CPricing是关系的所有者,当你在db中保存对象时,你还应该为CPricing设置计划。 您应该在保存之前执行Cpricing.setPl(plan) 之类的操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-18
    • 2019-07-24
    • 1970-01-01
    • 2023-03-16
    • 2023-03-19
    • 1970-01-01
    • 2019-11-28
    • 2013-06-28
    相关资源
    最近更新 更多