插入到 JPA 集合而不加载它
- 作者: 自古悲情最销魂
- 来源: 51数据库
- 2022-12-19
问题描述
我目前正在使用这样的代码向我的实体中的集合添加新条目.
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.
- 有没有办法(可能有查询)添加项目而不加载其余项目?在 SQL 中,它类似于 INSERT INTO AvatarAttributeOwnership(player, data, ...) VALUES({player}, ...);
目前唯一性是由 Set 和 AvatarAttributeOwnership.equals 的合约维护的,但我认为这将不再有效.无论如何我该如何执行?
- 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}, ...);
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.代码:
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; } ... }
推荐答案
试试 超懒集合:
@LazyCollection(LazyCollectionOption.EXTRA)
推荐阅读