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?

1
  • It looks like you probably want a fetch plan. Commented Nov 7, 2016 at 16:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.