I assume from the code in your findById method, and by the link to βlazy initialization does not workβ in the header, that you want to find the Aim object by its numerical identifier, as well as the associated User object.
To do this with lazy loading, you need to βgetβ the associated object, and (most importantly) you need to βgetβ one of the associated fields of the object.
So, the code inside the try block should be:
aim = aimRepository.findOne(Long.parseLong(aimId)); if (aim != null && aim.getUser() != null) { aim.getUser().getUserId();
Alternatively, if you have access to the log, you can use userId in a debug or trace log message:
if (aim != null && aim.getUser() != null) { logger.debug("Lazy-loaded User " + aim.getUser().getUserId()); }
This is an added benefit that you can debug when things are lazy.
By the way, we found out what a difficult way to make the search procedure throw an Exception when it does not find something bad. This is because you can use the find routine to find out if an entity does NOT exist. If this happens in a transaction, your exception may cause an unwanted rollback (unless you ignore it). It is better to return null and check this instead of using try ... catch .
source share