gpt4 book ai didi

java - 插入到 JPA 集合而不加载它

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:47 25 4
gpt4 key购买 nike

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

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

...

}

最佳答案

尝试 extra-lazy collections :

@LazyCollection(LazyCollectionOption.EXTRA)

关于java - 插入到 JPA 集合而不加载它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6814874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com