【问题标题】:Insert to JPA collection without loading it插入到 JPA 集合而不加载它
【发布时间】:2011-10-12 11:51:05
【问题描述】:

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

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

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

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

    ...

}

【问题讨论】:

  • 您确认我的建议有效吗?
  • @Bozho 还没有,因为我目前需要专注于让其他事情发挥作用而不是优化它,但我认为它可以工作。
  • 我也假设,但我没有尝试过,所以你现在可以取消标记接受的答案:)

标签: java hibernate jpa fetch jpql


【解决方案1】:

试试extra-lazy collections:

@LazyCollection(LazyCollectionOption.EXTRA)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2016-12-21
    • 2011-07-03
    • 2019-07-31
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多