Spring Data JPARepository: How to conditionally fetch children entites

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


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<Contact> contacts;

    @Transient
    public Collection<Contact> getContacts()
    {
        return contacts;
    }

    //getters & setters

}

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

public Account getAccountById(int accountId, Set<String> 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.