Reputation: 12481
I have a Hibernate entity with a composite key where the key is made up of a Long ID and a Timestamp. The ID should use a sequence generator.
MyEntity:
@Entity
@Table(name="MY_ENTITY")
public class MyEntity {
private MyEntityPk myEntityPk;
@EmbededId
public MyEntityPk getMyEntityPk() {
return myEntityPk;
}
// setter omitted
// other properties/getters/setters omitted
}
MyEntityPk:
public class MyEntityPk implements Serializable {
// version UID/hashCode()/equals() omitted
private Long myEntityId;
private Timestamp revisionTime;
@Column(name = "MY_ENTITY_ID", unique = true, nullable = false, precision = 13, scale = 0)
@GeneratedValue(strategy=GenerationType.AUTO, generator="HIBERNATE_SEQUENCE_GEN")
@SequenceGenerator(name="HIBERNATE_SEQUENCE_GEN", sequenceName="HIBERNATE_SEQUENCE")
public Long getMyEntityId() {
return myEntityId;
}
public void setMyEntityId(Long myEntityId) {
this.myEntityId = myEntityId;
}
@Column(name = "REVISION_TS", nullable = false)
public Timestamp getRevisionTime() {
return revisionTime;
}
public void setRevisionTime(Timestamp revisionTime) {
this.revisionTime = revisionTime;
}
}
The PK looks like it's wired up correctly. When I do a find all, I have a list of MyEntity objects where the MyEntityPk objects for each have an id and revisionTime from the database.
On insert, though, the following is giving me an error indicating that the MY_ENTITY_ID is null and the db won't allow a null value for that column. With our other entities, we can insert and leave our auto-generated IDs null and Hibernate knows to grab the next sequence from the db and use it in the entity. In this case, for some reason that's not happening:
MyEntity e = new MyEntity();
MyEntityPk pk = new MyEntityPk();
pk.setRevisionTime(new Timestamp(System.currentTimeMillis()));
//pk.setMyEntityId(5l); // see note below
e.setMyEntityPk(pk);
// setting a bunch of other entity parameters omitted
Session session = getSession();
session.saveOrUpdate( entity );
Ends up giving me:
// a bunch of stack trace omitted
Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("MY_SCHEMA"."MY_ENTITY"."MY_ENTITY_ID")
// more stack trace omitted
Note that if I set the PK object's ID manually, the insert will work.
Upvotes: 0
Views: 3325
Reputation: 1074
I only ever used composite keys which are references to other tables, but take a look at that one JPA Composite Key + Sequence
At first seems like bad news, but if you read the comments of the accepted answer you may get lucky
Upvotes: 1