Spring + Hibernate without lazy = LazyInitializationException

Viewed 102

I want to load all objects from a table without a lazy objects/children and list them on the page (Thymeleaf template), but I get a LazyInitializationException every time. I tried to convert Hibernate entity objects into a POJO that doesnt contains a lazy/unwanted object but with the same result. I also tried open-in-view parameter set to false...

Simple example:

Parent:

@Entity
public class DocumentDbe implements Serializable {

    public DocumentDbe(){
    }
    
    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;
    
    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    private DocumentFileDbe documentFile;
    ....
}

Child:

@Entity
public class DocumentFileDbe implements Serializable {

    public DocumentFileDbe(){}
    
    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Column
    @Lob
    private byte[] documentData;
    ...
 }

POJO:

public class DocumentDto implements Serializable {

    public DocumentDto(){
    }
    
    public DocumentDto(DocumentDbe doc){
        this.id = doc.getId();
    }
    ....
}

Controller:

@GetMapping("/list")
String getList(Model model) {
    List<DocumentDbe> docs;
    List<DocumentDto> data = new ArrayList<>();
    try (Session ses = sessionFactory.openSession()) {
        docs = ses.createQuery("FROM DocumentDbe").list();
        docs.forEach(doc -> {
            data.add(new DocumentDto(doc));
        });
    }
    model.addAttribute(MODEL_LIST_DATA, data);
    return "list";
}

EDIT: Thrown exception:

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/list.html]")] with root cause
org.hibernate.LazyInitializationException: could not initialize proxy - no Session

EDIT2: In DocumentDbe is relation with another object (EAGER this time so I was not paying attention to it) , which has reference to DocumentDbe again.. chained relationship and LazyInitializationException is created...

EDIT3: Although
This is modified and working controller, without POJO:

@GetMapping("/list")
String getList(Model model) {
    List<DocumentDbe> docs;
    try (Session ses = sessionFactory.openSession()) {
        docs = ses.createQuery("FROM DocumentDbe ORDER BY id DESC").list();
        docs.forEach(doc -> {
            doc.setDocumentFile(null);
            doc.getHistory().forEach(log ->{
                log.setDocument(null);
            });
        });
    }

    model.addAttribute(MODEL_ADMIN_DATA, docs);
    return "list";
}
1 Answers

In class DocumentDbe you have mark relation as Lazy. In default relation @ManyToOne and @OneToOne is as EAGER, so if you don't want Lazy, you have to change

@OneToOne(cascade = CascadeType.PERSIST)

If you want have @lob also as eager:

@Lob
@Basic( fetch = FetchType.EAGER )
Related