It is not recommended to store objects as a primary key. There are some limitations to using the query language, and JPA 1.0 does not support it. In addition, there is no need to use entities as the primary key. Think about it. If you want, pay particular attention to the following question.
, @Entity @Embeddable
, .
public class GroupMembershipPK implements Serializable {
private User user;
private Group group;
}
public class GroupMembershipPK implements Serializable {
private Integer userId;
private Integer groupId;
}
, JPA , (JPA , , ). ,
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanceof GroupMembershipPK))
return false;
GroupMembershipPK other = (GroupMembershipPK) o;
if(!(getUserId().equals(other.getUserId()))
return false;
if(!(getGroupId().equals(other.getGroupId()))
return false;
return true;
}
. , JPA - - . - , JPA .
, ?
User user = new user();
Group group = new Group();
entityManager.save(user);
entityManager.save(group);
entityManager.flush();
UserGroup userGroup = new UserGroup();
userGroup.setId(new UserGroup.UserGroupId(user.getId(), group.getId()));
entityManager.save(userGroup);
, UserGroup?
public class UserGroup {
private UserGroupId id;
@Embeddable
public static class UserGroupId implements Serializable {
private Integer userId;
private Integer groupId;
public UserGroupId() {}
public UserGroupId(Integer userId, Integer groupId) {
this.userId = userId;
this.roupId = groupId;
}
}
@EmbeddedId
public UserGroupId getId() {
return this.id;
}
public setId(UserGroupId id) {
this.id = id;
}
}
IdClass. . IdClass
,