Spring provides two mechanisms that can be used to limit data to be fetched.
Projections
Projections can help you to reduce data, retrieved from database, by setting what exactly attributes you want to fetch. Example:
@Entity class Person { @Id UUID id; String firstname, lastname; @OneToOne Address address; } @Entity static class Address { @Id UUID id; String zipCode, city, street; } interface NamesOnly { String getFirstname(); String getLastname(); } @Repository interface PersonRepository extends Repository<Person, UUID> { Collection<NamesOnly> findByLastname(String lastname); } Entity graph
Annotation EntityGraph can help you to reduce amount of queries to database, by setting what exactly related entities you need to fetch.
Example:
@Entity @NamedEntityGraph(name = "GroupInfo.detail", attributeNodes = @NamedAttributeNode("members")) public class GroupInfo { @Id UUID id; @ManyToMany //default fetch mode is lazy. List<GroupMember> members = new ArrayList<GroupMember>(); } @Repository public interface GroupRepository extends CrudRepository<GroupInfo, String> { @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD) GroupInfo getByGroupName(String name); //Despite of GroupInfo.members has FetchType = LAZY, it will be fetched because of using EntityGraph } There are two types of EntityGraph:
EntityGraphType.LOAD- is used to specify an entity graph, attributes that are specified by attribute nodes of the entity graph are treated asFetchType.EAGERand attributes that are not specified are treated according to their specified or defaultFetchType.EntityGraphType.FETCH- is used to specify an entity graph, attributes that are specified by attribute nodes of the entity graph are treated asFetchType.EAGERand attributes that are not specified are treated asFetchType.LAZY.
PS: Also remember that you can set lazy fetch type: @ManyToOne(fetch = FetchType.LAZY) and JPA will not fetching child entities when parent is being fetched. If fetch type and entity graph will not solve your problem, I would suggest you to consider another approaches to work with data.