Saving a entity with multiple lazy-associations

Refresh

March 2019

Views

4 time

0

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:

Entites:

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;
    @NotNull
    private idFoo;

    /* Getters and Setters Ommited */
}

Service to persist Bar

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

        //Getting a reference do foo            
        bar.setFoo(fooRepository.getOne(dto.getIdFoo()));           

        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
                */
                bar.setMessage(bar.getFoo().getDefaultMessage());
        } else {
                bar.setMessage(dto.getMessage);
        }

        barRepository.save(bar);
}

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?

Tks!

0 answers