Spring Data JPARepository: How to conditionally fetch children entites

前端 未结 5 1381
余生分开走
余生分开走 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 14:54

    The lazy fetch should be working properly if no methods of object resulted from the getContacts() is called.

    If you prefer more manual work, and really want to have control over this (maybe more contexts depending on the use case). I would suggest you to remove contacts from the account entity, and maps the account in the contacts instead. One way to tell hibernate to ignore that field is to map it using the @Transient annotation.

    @Entity
    @Table(name = "accounts")
    public class Account
    {
        protected String accountId;
        protected Collection contacts;
    
        @Transient
        public Collection getContacts()
        {
            return contacts;
        }
    
        //getters & setters
    
    }
    

    Then in your service class, you could do something like:

    public Account getAccountById(int accountId, Set fetchPolicy) {
        Account account = accountRepository.findOne(accountId);
        if(fetchPolicy.contains("contacts")){
            account.setContacts(contactRepository.findByAccountId(account.getAccountId());
        }
        return account;
    }
    

    Hope this is what you are looking for. Btw, the code is untested, so you should probably check again.

提交回复
热议问题