我在 JPA + Hibernate、Player
和 AvatarAttributeOwnership
中有这些实体。前者有后者的Set
,后者定义了它拥有哪些头像属性。
@Entity
public class Player implements Serializable {
@Id
@GeneratedValue
private long id;
@OneToMany(fetch=FetchType.LAZY,mappedBy="owner",cascade=CascadeType.ALL)
private Set<AvatarAttributeOwnership> ownedAvatarAttributes;
...
}
@Entity
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"owner","gender","type","attrId"}))
public class AvatarAttributeOwnership implements Serializable {
@Id
@GeneratedValue
@SuppressWarnings("unused")
private long id;
@ManyToOne
@JoinColumn(name="owner")
private Player owner;
// these three columns define the attribute (i.e. are attribute's key)
@Column
private String attrId;
@Column
private String gender;
@Column
private String type;
@Column
private Date ownedSince;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + attrId.hashCode();
result = prime * result + gender.hashCode();
result = prime * result + owner.hashCode();
result = prime * result + type.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
AvatarAttributeOwnership other = (AvatarAttributeOwnership) obj;
if (!attrId.equals(other.attrId)) return false;
if (gender != other.gender) return false;
if (!owner.equals(other.owner)) return false;
if (!type.equals(other.type)) return false;
return true;
}
}
AvatarAttributeOwnerships 是这样创建的:
player = em.find(Player.class, playerId);
player.getAvatarAttributeOwnership().add(new AvatarAttributeOwnership(player, attrId, gender, type, new Date()));
em.persist(player);
我能否去掉 AvatarAttributeOwnership
中的所有者引用,同时保留在那里定义的唯一约束?
最佳答案
您可以通过定义单向多对一关联。这将生成一个连接表,其中一列是所有者的 ID(在您的例子中是玩家),另一列是 child 的 ID(AvatarAttributeOwnership)。参见 http://docs.jboss.org/hibernate/core/3.3/reference/en/html/associations.html#assoc-unidirectional-join-12m用于解释(注意映射中的 unique=true )
关于java - 摆脱 JPA 中对所有者的冗余引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6625930/