简体   繁体   中英

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<>();//

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM