DataIntegrityViolationException: could not execute statement. When perform save operation for @OneToOne JPA mapping

huangapple go评论113阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年7月28日 15:51:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63129395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定