Saving a entity with multiple lazy-associations


March 2019


4 time


I have a scenario where I need to save an entity with multiple associations but I don't want to retrieve these associations if not needed.

I will try to give a simple example:


public class Foo {
    private Long idFoo;
    private String defaultMessage;

    /* Getters and Setters Ommited */   

public class Bar {
    private Long idBar; 
    private String message;

    /*one-to-one lasy assoc*/   
    private Foo foo;

    /* Getters and Setters Ommited */

Bar input DTO

Public class BarInputDTO {
    private String message;
    private idFoo;

    /* Getters and Setters Ommited */

Service to persist Bar

public void saveAsEntity(BarInputDTO dto) {
        Bar bar = new Bar();

        //Getting a reference do foo            

        if (dto.getMessage().equals("")) {
                * I just want to load the association if there is no message.
                * but get - LazyInitializationException: could not initialize proxy - no session
        } else {

As the comment says, I just want to load the association if there is no message. But in this situation I get a LazyInitializationException. If a message is informed Bar is saved.

I understand that fooRepository.getOne open and close a transaction when it is called, then when I call getDefaultMessage there is no session. I supposed that adding an @Transaction annotation to the method would solve the problem but I was wrong.

Of course I could get the Foo object directly from the fooRepo inside the if clause but my real scenario is a bit more complex and it would be a very repetitive task.

Is there something I am missing to make it work?


0 answers