插入JPA集合而不加载它

Bar*_*lom 7 java hibernate jpa fetch jpql

我目前正在使用这样的代码向我的实体中的集添加新条目.

player = em.find(Player.class, playerId);
player.getAvatarAttributeOwnership().add(new AvatarAttributeOwnership(...));
Run Code Online (Sandbox Code Playgroud)

它有效,但每次我想添加一个项目时,整个集合都会被加载.

  1. 有没有办法(可能有查询)添加项目而不加载其余项目?在SQL中它会是这样的INSERT INTO AvatarAttributeOwnership(player, data, ...) VALUES({player}, ...);
  2. 目前唯一通过合同维护SetAvatarAttributeOwnership.equals,但我相信,这将不再工作.我怎么能强制执行呢?

我正在使用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;
    }

    ...

}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 5

尝试非常懒的集合:

@LazyCollection(LazyCollectionOption.EXTRA)
Run Code Online (Sandbox Code Playgroud)