[英]JPA ConstraintViolationException the forgein key as value null
I migration to JPA persistent with Hibernate. 我使用Hibernate永久迁移到JPA。 I test with two Entity and when persist a entity, I receive the exception on constrains violation for the value null of the forgein key.
我使用两个Entity进行测试,当持久化一个实体时,forgein键的null值收到约束违例的异常。
This is structure the table of database: 这是数据库表的结构:
CREATE TABLE AZIENDA
(AZN_ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
CREATE TABLE AGENTE
(AGN_ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
AGN_IDAZN INTEGER NOT NULL,
...
CONSTRAINT FK_AGN_AZN FOREIGN KEY (AGN_IDAZN) REFERENCES AZIENDA (AZN_ID) ON DELETE CASCADE);
The Entity: 实体:
@Entity
@Table(name="AZIENDA")
public class Azienda {
@Column(name="AZN_ID")
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
...
@Entity
@Table(name="AGENTE")
public class Agente {
@Column(name="AGN_ID")
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="AGN_IDAZN")
@JoinColumn(name="FK_AGN_AZN", referencedColumnName="AZN_ID")
@ManyToOne()
// @ManyToOne(optional=true, cascade=CascadeType.PERSIST)
@Transient
private Azienda azienda;
...
First all retrieve the object 'Azienda' from database, after instance a new 'Agente' entity and set the property 'azienda', when create and persist a new entity 'Agente', I receive ConstraintViolationExcpetion The column 'AGN_IDAZN' can't containt the value null, but the instance 'Azienda' not is null. 首先都是从数据库中检索对象“ Azienda”,实例之后是一个新的“ Agente”实体并设置属性“ azienda”,当创建并保留一个新实体“ Agente”时,我收到ConstraintViolationExcpetion列“ AGN_IDAZN”无法包含值null,但实例'Azienda'不是null。
Thanks!! 谢谢!!
Try to remove @Transient
annotation from azienda
property of Agente
class. 尝试删除
@Transient
从注释azienda
财产Agente
类。
@Transient
annotation means that entity fields are fields that do not participate in persistence and their values are never stored in the database. @Transient
注释表示实体字段是不参与持久性的字段,并且它们的值永远不会存储在数据库中。
I realized in a different way the functionality @Transient annotation... Thanks!! 我以不同的方式意识到了@Transient批注的功能...谢谢!
This is the Entity changes: 这是实体更改:
@Entity
@Table(name="AGENTE")
public class Agente {
...
@JoinColumn(name="AGN_IDAZN", referencedColumnName="AZN_ID")
@ManyToOne(cascade=CascadeType.PERSIST)
private Azienda azienda;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.