英文:
DataIntegrityViolationException: could not execute statement. When perform save operation for @OneToOne JPA mapping
问题
I am getting "org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement" exception while saving the object into the repository.
Requirement: Plan will have only one Cpricing Object so I have added @OneToOne mapping. Below is the expected table structure.
Plan table
id | planname
Cpricing table
id | cdata | plan_id(fk)
I have below code changes in Entity classes:
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;
}
An Exception is thrown when trying to save Plan object containing CPricing object.
Is the mapping correct?
英文:
I am getting "org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement" exception while saving the object into the repository.
Requirement: Plan will have only one Cpricing Object so I have added @OneToOne mapping. Below is the expected table structure.
Plan table
-------------
id | planname
Cpricing table
----------
id | cdata | plan_id(fk)
I have below code changes in Entity classes:
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;
}
An Exception is thrown when trying to save Plan object containing CPricing object.
Is the mapping correct ?
答案1
得分: 1
在CPricing
一侧放置@JoinColumn
,因此CPricing
是关系的所有者,当您将对象保存到数据库中时,您还应该为CPricing
设置计划。
在保存之前,您应该执行类似Cpricing.setPl(plan)
的操作。
英文:
Here you put @JoinColumn
on CPricing
side, so CPricing
is the owner of relation you should also set plan for CPricing
when you save object in db.
You should do something like Cpricing.setPl(plan)
before save.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论