Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quarkus lazy initialize

I am getting the following error whenever I try to return all records using the rest method.

Error:

Internal Server Error Error handling e6059ae8-5970-4ac2-a1fa-7325768944bb-1, org.jboss.resteasy.spi.UnhandledException: javax.ws.rs.ProcessingException: RESTEASY008205: JSON Binding serialization error javax.json.bind.JsonbException: Unable to serialize property 'task' from model.Board

org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [model.Board.task] - no session and settings disallow loading outside the Session

first model

@Entity
public class Task{

    @Id
    @Column(name = "TaskID")
    public Long taskId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "BoardID")
    public Board board;

    @Column(name = "Title")
    public String title;

    @Column(name = "Description", length = 1000)
    public String description;
}

second model

@Entity
public class Board{

    @Id
    @Column(name = "BoardID")
    public Long boardId;

    @OneToMany(mappedBy = "board")
    public List<Task> task = new ArrayList<>();;

    @Column(name = "Title")
    public String title;

    @Column(name = "Position")
    @NotNull
    public int position;
}

repository :

@ApplicationScoped
@Transactional
public class BoardRepository implements PanacheRepository<Board> {
}

example REST method

@Transactional
@ApplicationScoped
public class ExampleResource {

    @Inject
    BoardRepository boardRepository;

    @Inject
    TaskRepository taskRepository;

    @GET
    @Transactional
    public List<Board> getAll() {
        return boardRepository.listAll();
    }
}
like image 670
Logan_on Avatar asked Jun 18 '20 13:06

Logan_on


1 Answers

The issue is, that during JSON serialization, it tries to serialize the task list which has a back reference to Board and something in that graph might not be initialized. Also, the serialization could lead to a cycle which can't be modeled directly in JSON so you have to resolve this somehow.

  • Use @JsonIgnore to exclude a field from JSON serialization
  • Use a DTO, preferrably with Blaze-Persistence Entity-Views for best performance which has a Quarkus integration, that only models a subset of the state that you really want to expose
like image 55
Christian Beikov Avatar answered Oct 25 '22 00:10

Christian Beikov