I don't know since when this is possible, but I just created 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, like this:
@Entity
public class A implements Serializable {
@Id
@Column
String a;
@Id
@Column
String b;
@Column
String c;
}
Works like a charm!!
Is there still any reason to use @EmbeddedId
or @IdClass
?
And: Is this part of JPA 2.1 or an Hibernate feature?
JPA requires a primary key class of some sort be defined for composite primary keys. In practice though, this seems required mostly for the EntityManager find and getReference calls that require a pk class instance. Implementations may have their own pk representation that you can use for these calls, but will not be portable.
来源:https://stackoverflow.com/questions/19009572/super-simple-composite-key-without-embeddedid-or-idclass