Super simple composite key without @EmbeddedId or @IdClass

I don’t know when this is possible, but I just created the composite keys the way I always wanted: no @EmbeddedId and no @IdClass required !!

  • Spring 4.0.0.M3
  • Hibernate 4.3.0.Beta4
  • JPA 2.1

User.java

 @Entity public class User { @Id ... @OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true) private List<GroupUser> groupUsers; } 

Group.java

 @Entity public class Group { @Id ... @OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true) private List<GroupUser> groupUsers; } 

GroupUser.java

 @Entity public class GroupUser implements Serializable { @Id @ManyToOne @JoinColumn(name="Group_id") private Group group; @Id @ManyToOne @JoinColumn(name="User_id") private User user; @Id @Column private String s; @Column private int i; } 

And here is what MySQL says:

  USER GROUP_USER GROUP ------ ------------------------- ------- id User_id (PK, NOT NULL) id Group_id (PK, NOT NULL) s (PK, NOT NULL) i (DEFAULT NULL) 

GROUP_USER details:

  • PRIMARY KEY: User_id, Group_id, s
  • INDEX # 1 / FOREIGN KEY: User_id
  • INDEX # 2 / FOREIGN KEY: Group_id

I also did some other tests, for example:

 @Entity public class A implements Serializable { @Id @Column String a; @Id @Column String b; @Column String c; } 

It works like a charm!


Is there any reason to use @EmbeddedId or @IdClass ?

And: Is this part of the function JPA 2.1 or Hibernate?

+2
source share
1 answer

JPA requires that a primary key class of a particular type be defined for composite primary keys. In practice, however, this seems to be required mainly for calls to EntityManager find and getReference, which require an instance of the pk class. An implementation may have its own pk representation, which you can use for these calls, but will not be portable.

+2
source

All Articles