2011-07-25 52 views
6

我目前正在使用这样的代码向我的实体中的集合添加一个新条目。插入JPA集合而不加载它

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([email protected](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; 
    } 

    ... 

} 
+0

你确认我的建议的作品? – Bozho

+0

@Bozho还没有,因为我目前需要专注于使其他一些工作而不是优化,但我认为它的工作原理。 –

+0

我也假设,但我没有尝试过,所以你现在可以取消接受的答案:) – Bozho

回答