0

I have an entity with a lot of relationships. I cannot change them because the mapping is used in numerous parts of the code.

In only one use case, I would like to be able to load only the entities and not their relationships.

I made a simple CRUDRepository like this :

public interface EmployeeRepository extends CrudRepository<Employee, UUID> {
  List<Employee> findByCompanyId(UUID companyId);
}

How can I load Employee without their relationships without altering the mapping annotations?

I tried :

public interface EmployeeRepository extends CrudRepository<Employee, UUID> {
  List<Employee> findLazyByCompanyId(UUID companyId);
}

This compiles but the entities are still not lazy loaded. I am surprised that the keyword 'Lazy' is accepted if lazy loading is not done.

Any idea?

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148

1 Answers1

1

There is no easy way. Possibly no way full stop -that would depend on your persistence provider. That is why should mostly define relationships as lazy and load eagerly when required rather than the other way around.

See, for example:

JPA and eclipselink - Overriding FetchType.Eager

and

How to override FetchType.EAGER to be lazy at runtime

All I could suggest would be to use a constructor expression to either return a list of unmanaged users.

http://www.objectdb.com/java/jpa/query/jpql/select#Result_Classes_Constructor_Expressions_

or, more simply use a Spring Data projection to return a subset of the data:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

public interface EmployeeRepository extends CrudRepository<Employee, UUID> {
  EmployeeSummaryProjection findByCompanyId(UUID companyId);
}

@Projection(name="EmployeeSummaryProjection", types = {Employee.class})
interface EmployeeSummaryProjection{

   /declare methods matching the data you wish to return
}

If the data returned is read-only then either of the above may be a solution.

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110