Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two classes documentlog and documentversion(with primary keys: int doc_id and int docVersionID) with a many-to-one relationship. I used a composite key class called CompundKey to manage the compound primary key. I need to auto increment docversionID but I am not able to do that. Could you please help me in this regard?

@Entity
@Table(name = "Documentversion", schema = "DocumentManagement")
public class DocumentVersion implements Serializable { 

 private CompoundKey id;
 private List<DocumentLog> documentLog;

 @OneToMany(mappedBy="documentVersion", targetEntity=DocumentLog.class,  
   cascade ={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
 public List<DocumentLog> getDocumentLog() {
  return documentLog;
 }
 public void setDocumentLog(List<DocumentLog> documentLog) {
  this.documentLog = documentLog;
 }

 @EmbeddedId 
 @AttributeOverride(name="doc_Id", column=@Column(name="doc_Id") )
 public CompoundKey getId() {
  return id;
 }
 public void setId(CompoundKey id) {
  this.id = id;
 } 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
105 views
Welcome To Ask or Share your Answers For Others

1 Answer

The documentation is a bit confusing on this topic...

To my knowledge, composite keys always had to be assigned by the application (i.e. non generated) at least with standard JPA but also Hibernate Core:

8.4. Components as composite identifiers

...

You cannot use an IdentifierGenerator to generate composite keys. Instead the application must assign its own identifiers.

But things might be a bit different in practice (see HHH-2060 and/or this thread for an alternative using a CompositeUserType together with an IdentifierGenerator).

Now, the most confusing part, from the Hibernate Annotations 3.5 documentation:

2.2.3.2.4. Partial identifier generation

Hibernate supports the automatic generation of some of the identifier properties. Simply use the @GeneratedValue annotation on one or several id properties.

...

You can also generate properties inside an @EmbeddedId class.

(and please also read the warning from the Hibernate Team against using this feature).

I don't have any practical experience with it though.

References


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...