简体   繁体   中英

Hibernate @EmbeddedId

Here is my problem

IdComposite class:

@Embeddable
public class IdComposite implements Serializable{

 @Column(name = "code1", nullable = false)
 private String code1;

 @Column(name = "code2", nullable = false)
 private String code2;

// getters, setters, hashCode & equals

}

MyEntity class:

@Entity
@Table(name = "table")
public class MyEntity {

 @EmbeddedId
 private IdComposite comId;

 @ManyToOne(fetch = FetchType.LAZY, cascade = {})
 @JoinColumn(name = "a_id", nullable = false, updatable = false, insertable = false)
 private A a;

 // constructors, getters setters, e t.c.

}

DaoClass fragment:

MyEntity myEntity = new MyEntity();
A a = new A();
a.setId(5);
myEntity.setA(a);
IdComposite id = new IdComposite();
id.setCode1("1");
id.setCode2("2");
myEntity.setComId(id);
getSession().save(myEntity);

Hibernate result:

Hibernate: insert into table (code1, code2) values (?, ?) SQL Error: 1400, SQLState: 23000 ORA-01400: cannot insert NULL into "table"."a_id")

What is wrong?

Edited:

Ok, I've changed the code in that way:

MyEntity class:

@Entity
@Table(name = "table")
public class MyEntity {

 @EmbeddedId
 private IdComposite comId;

 @Column(name = "a_id", nullable = false, updatable = false, insertable = false)
 private Long aId;

 // constructors, getters setters, e t.c.

}

DaoClass fragment:

MyEntity myEntity = new MyEntity();
Long aId = 5L;
A a = (A) getSession().get(A.class, aId);
if (a == null || a.getId() != 5) { return }
myEntity.setAId(a.getId());
IdComposite id = new IdComposite();
id.setCode1("1");
id.setCode2("2");
myEntity.setComId(id);
getSession().save(myEntity);

Hibernate result:

Hibernate: insert into table (code1, code2) values (?, ?) SQL Error: 1400, SQLState: 23000 ORA-01400: cannot insert NULL into ("TABLE"."A_ID")

Solved

The problem was here:

, insertable = false)

So, hibernate generate sql without a_id field that caused error

It doesn't seems to come from composite id, but from A. try to save A instance

MyEntity myEntity = new MyEntity();
A a = new A();
a.setId(5);
a= getSession().save(a);
myEntity.setA(a);
IdComposite id = new IdComposite();
id.setCode1("1");
id.setCode2("2");
myEntity.setComId(id);
getSession().save(myEntity);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM