我在JPA + Hibernate,PlayerAvatarAttributeOwnership中有这些实体。前者具有后者的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的列(在您的情况下为Player)和具有孩子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/

10-11 17:17