Insert to JPA collection without loading it

醉酒当歌 提交于 2019-12-23 09:19:32

问题


I'm currently using code like this to add a new entry to a set in my entity.

player = em.find(Player.class, playerId);
player.getAvatarAttributeOwnership().add(new AvatarAttributeOwnership(...));

It works, but every time I want to add one item, the whole set is loaded.

  1. Is there a way (with a query maybe) to add the item without loading the rest? In SQL it would be something like INSERT INTO AvatarAttributeOwnership(player, data, ...) VALUES({player}, ...);
  2. 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?

I'm using JPA2+Hibernate. Code:

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

    ...

}

回答1:


Try extra-lazy collections:

@LazyCollection(LazyCollectionOption.EXTRA)


来源:https://stackoverflow.com/questions/6814874/insert-to-jpa-collection-without-loading-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!