Hello all,
Using Hibernate + annotations, I'm trying to do the following:
Two entities, Entity1 and Entity2.
* Entity1 contains a primary key generated by a DB Sequence
* Entity2 primary key has a composite id, one of the properties of this Id has a relationship of @ManyToOne to Entity 1 primary key.
* I need to persist Entity one, with a list of Entity 2 objects.
I had this working on TopLink but unfortunately, I can't make it work on Hibernate.
Here is my code:
Code:
@Entity
public class Entity1 {
@SequenceGenerator(name="ONE_GEN",sequenceName="ONE_SEQ",allocationSize=1)
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ONE_GEN")
private Long entity1_id;
//bi-directional many-to-one association to ObjetosCambio
@OneToMany(cascade={CascadeType.PERSIST},mappedBy="entity1")
private List<Entity2> entity2List;
...
}
Code:
@Entity
public class Entity2 implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private Entity2PK pk = new Entity2PK();
//bi-directional many-to-one association to Cambios
@ManyToOne
@JoinColumn(name="entity1_id", insertable=false, updatable=false)
private Entity1 entity1;
...
}
Code:
@Embeddable
public class Entity2PK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="entity1_id")
private Long entity1_id;
@Column(name="entity3_id")
private Long ientity3_id;
...
}
Code:
List<Entity2> entity2List = new ArrayList();
Entity1 entity1 = new Entity1();
Entity3 entity3 = xxx; // this xxx value is not relevant
Entity2 entity2 = new Entity2();
entity2.setEntity1(entity1); //AT THIS TIME THIS "Entity1" DOES NOT HAVE ITS ID, ITS SUPPOSED TO BE GENERATED AT PERSISTENCE TIME
Entity2PK pK = new Entity2PK();
pK.setEntity3_id(entity3.getEntity3_id());
entity2.setEntity2_id(pK);
entity2List.add(entity2);
entity1.setEntity2List(entity2List);
em.persist(cambio);
Code:
ERROR:
15:23:25,717 WARN [JDBCExceptionReporter] SQL Error: 1400, SQLState: 23000
15:23:25,717 ERROR [JDBCExceptionReporter] ORA-01400: no se puede realizar una inserciĆ³n NULL en ("CDC"."ENTITY2"."ENTITY1_ID")
15:23:25,717 WARN [JDBCExceptionReporter] SQL Error: 1400, SQLState: 23000
15:23:25,717 ERROR [JDBCExceptionReporter] ORA-01400: no se puede realizar una inserciĆ³n NULL en ("CDC"."ENTITY2"."ENTITY1_ID")
15:23:25,717 ERROR [AbstractFlushingEventListener] Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
Thanks in advance,
JM.-