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();
开发者_StackOverflow中文版 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).
精彩评论