Spring Data JPARepository: How to conditionally fetch children entites

前端 未结 5 1388
余生分开走
余生分开走 2020-12-08 14:28

How can one configure their JPA Entities to not fetch related entities unless a certain execution parameter is provided.

According to Spring\'s documentation, 4.3.9

5条回答
  •  悲哀的现实
    2020-12-08 15:02

    You can use @Transactional for that.

    For that you need to fetch you account entity Lazily.

    @Transactional Annotations should be placed around all operations that are inseparable.

    Write method in your service layer which is accepting one flag to fetch contacts eagerly.

    @Transactional
    public Account getAccount(String id, boolean fetchEagerly){
        Account account = accountRepository.findOne(id);
    
        //If you want to fetch contact then send fetchEagerly as true
        if(fetchEagerly){
            //Here fetching contacts eagerly
            Object object = account.getContacts().size();   
        }
    }
    

    @Transactional is a Service that can make multiple call in single transaction without closing connection with end point.

    Hope you find this useful. :)

    For more details refer this link

提交回复
热议问题