简体   繁体   中英

New entity in a set is not persisted

JPA + Hibernate

I'm using this code to create a new AvatarAttributeOwnership ( AAO ) and assign it to a Player. However, the new AAO is not persisted to the database.

                // get player
                player = em.find(Player.class, playerId);

                ....

                // give attribute
                player.getAvatarAttributeOwnership().add(new AvatarAttributeOwnership(player, atr.key()));

                // save
                em.persist(player);

Entities:

@Entity
public class Player implements Serializable {



    @Id
    @GeneratedValue
    private long id;

    @OneToMany(fetch=FetchType.LAZY,mappedBy="owner")
    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;

    ...

    @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;
    }

}

Not sure where to place it but I think you need a cascade="all" attribute probably in players' onetomany (not sure I'm still using hbm files).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM