Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert to JPA collection without loading it

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

    ...

}
like image 381
Bart van Heukelom Avatar asked Jul 25 '11 10:07

Bart van Heukelom


1 Answers

Try extra-lazy collections:

@LazyCollection(LazyCollectionOption.EXTRA)
like image 199
Bozho Avatar answered Nov 13 '22 00:11

Bozho