Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading collections with JPA / EclipseLink

Is there any way that each child of a collection will be loaded individually by EclipseLink?

I have got the two Entities:

@Entity
public class A {

    private List<Item> collection = new LinkedList<Item>();

    @OneToMany(fetch = FetchType.LAZY)
    public List<Item> getCollection() {
        return this.collection;
    }

    public void setCollection (List<Item> collection) {
        this.collection = collection;
    }
}

@Entity
public class Item {

    private byte[] data;

    @Lob
    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }
}

My collection contains a large number of items, hence I don’t want EclipseLink to load all children when I access e.g. only the first item. But calling a.getCollection().get(0).getData() results in loading all items of the collection in memory. Is there a way to avoid this? (And only loading the first item in memory)

like image 309
user1164016 Avatar asked Dec 07 '25 12:12

user1164016


2 Answers

Add (actually mappedBy should rather be on the OneToMany side, but for the sake of simplicity):

@ManyToOne(mapped="collection")
private A a;

to the Item class and fetch each item by foreign key individually:

SELECT i
FROM Item i
WHERE i.a = :a

Where :a parameter is an instance of A.

like image 101
Tomasz Nurkiewicz Avatar answered Dec 09 '25 03:12

Tomasz Nurkiewicz


If you never want to read in the collection, then do not map it. Instead just query for it.

like image 37
James Avatar answered Dec 09 '25 01:12

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!