我目前正在使用这样的代码将新条目添加到我的实体中的集合中。
player = em.find(Player.class, playerId);
player.getAvatarAttributeOwnership().add(new AvatarAttributeOwnership(...));
它有效,但每次我想添加一个项目时,都会加载整套项目。
- 有没有办法(可能需要查询)添加该项目而不加载其余项目?在 SQL 中它会是这样的
INSERT INTO AvatarAttributeOwnership(player, data, ...) VALUES({player}, ...);
Currently uniqueness is maintained by the contract of Set
and AvatarAttributeOwnership.equals
, but I assume that won't work anymore. How can I enforce it anyway?
我正在使用 JPA2+Hibernate。代码:
@Entity
public class Player implements Serializable {
@Id
@GeneratedValue
private long id;
@ElementCollection(fetch=FetchType.LAZY)
// EDIT: answer to #2
@CollectionTable(uniqueConstraints=@UniqueConstraint(columnNames={"Player_id","gender","type","attrId"}))
Set<AvatarAttributeOwnership> ownedAvatarAttributes;
...
}
@Embeddable
public class AvatarAttributeOwnership implements Serializable {
@Column(nullable=false,length=6)
@Enumerated(EnumType.STRING)
private Gender gender;
@Column(nullable=false,length=20)
private String type;
@Column(nullable=false,length=50)
private String attrId;
@Column(nullable=false)
private Date since;
@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 (!type.equals(other.type)) return false;
return true;
}
...
}
Try 超惰性集合 https://sites.google.com/a/pintailconsultingllc.com/java/hibernate-extra-lazy-collection-fetching:
@LazyCollection(LazyCollectionOption.EXTRA)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)