[英]Super simple composite key without @EmbeddedId or @IdClass
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!! 我不知道什么时候开始,但是我只是按照我一直想要的方式创建了复合键:不需要
@EmbeddedId
和@IdClass
!
User.java : User.java :
@Entity
public class User {
@Id
...
@OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true)
private List<GroupUser> groupUsers;
}
Group.java : Group.java :
@Entity
public class Group {
@Id
...
@OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true)
private List<GroupUser> groupUsers;
}
GroupUser.java : 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: 这是MySQL所说的:
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: GROUP_USER
详细信息:
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
? 仍然有任何理由使用
@EmbeddedId
或@IdClass
吗?
And: Is this part of JPA 2.1 or an Hibernate feature? 并且:这是JPA 2.1的一部分还是Hibernate功能?
JPA requires a primary key class of some sort be defined for composite primary keys. JPA要求为组合主键定义某种主键类。 In practice though, this seems required mostly for the EntityManager find and getReference calls that require a pk class instance.
但是实际上,这似乎是大多数需要pk类实例的EntityManager find和getReference调用所必需的。 Implementations may have their own pk representation that you can use for these calls, but will not be portable.
实现可能具有自己的pk表示形式,您可以将其用于这些调用,但不能移植。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.