How can I use generated value within composite keys?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 12:27:23

问题


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;
 } 
}

回答1:


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



回答2:


It is possible to declared your own generator for @EmbeddedId to use sequence for Id generation.

Also, you'll need to declare fake entity to create sequence automatically.



来源:https://stackoverflow.com/questions/4120414/how-can-i-use-generated-value-within-composite-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!