I have a lazily fetched field in my entity
@ElementCollection(fetch = LAZY)
private List<String> emails;
And my transaction boundary stops at service class, I don't want to keep it open while rendering the view. I want my service classes to return detached entities.
In my service class I tried calling the getters but that seem to be erased by the compiler -- maybe it's an optimization for a statement that appear to do nothing
/* User Service class */
@Transactional
public List<User> getAllUsers() {
List<User> users = new ArrayList();
for(User u : userRepo.findAll()) {
u.getEmails(); // <-- this seem to be erased by the compiler optimization.
users.add(u);
}
return users;
}
Hence I'm forced to print the lazy field into TRACE log so that it won't clutter the production logs. Doing this will ensure the lazy field is pre-populated before the entities are detached:
LOG.trace(u.getEmails().toString());
However this solution isn't pretty at all. Is there any better way to do this?
I don't want to mark the field as EAGER because I have another service method that purposely skips the relationship for efficiency.