Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use generated value within composite keys?

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;
 } 
}
like image 706
Nick Avatar asked Nov 08 '10 00:11

Nick


1 Answers

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

  • Hibernate Core Reference Guide
    • 8.4. Components as composite identifiers
  • Hibernate Annotations 3.5 Reference Guide
    • 2.2.3.2.4. Partial identifier generation
like image 124
Pascal Thivent Avatar answered Sep 17 '22 22:09

Pascal Thivent