Terry Yue
Terry Yue

Reputation: 11

JPA how to lazily load collection?

Please advise how to lazily load the map "Groupunit_from"? How to open a JPA session and transaction?

 @ElementCollection(targetClass=String.class,fetch=FetchType.LAZY)
    @CollectionTable(name="place_definer_groupunit_from",joinColumns=@JoinColumn(name="groupunit_from"))
    @MapKeyColumn(name="id")
    @MapKeyClass(String.class)
    @Column(name="ordinal",nullable=false)
    private Map<String,String> Groupunit_from=new HashMap<>();//

Upvotes: 0

Views: 156

Answers (2)

jiket
jiket

Reputation: 57

you already mentioned "fetch=FetchType.LAZY" so jpa will load this elements lazily. If you observe the queries fired in the application while debugging, you will observe that the queries for populating this map will be fired when you use this map for the first time in your java code.

Upvotes: 0

yashjain12yj
yashjain12yj

Reputation: 783

Collections are loaded Lazily by default.

You don't have to specify anything to load a collection lazily.

To initialize a session and Transaction in JPA

EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistentUnitName");
EntityManager em = emf.createEntityManager();

// to begin a transaction
em.getTransaction().begin();

// here you can flush or persist

// to commit a transaction
em.getTransaction().commit();

Upvotes: 2

Related Questions