JPA + Hibernate
Я использую этот код, чтобы создать новый AvatarAttributeOwnership
(AAO
) и назначить его игроку. Однако новый AAO
не сохраняется в базе данных.
// get player
player = em.find(Player.class, playerId);
....
// give attribute
player.getAvatarAttributeOwnership().add(new AvatarAttributeOwnership(player, atr.key()));
// save
em.persist(player);
Объекты:
@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;
}
}