Почему я получаю org.hibernate.LazyInitializationException при использовании JOIN?

Не могу понять, почему всё ещё получаю org.hibernate.LazyInitializationException при JOIN

Репозиторий:

package ...
import ...

public interface SobjectRepo extends CrudRepository<Sobject, Long> {
    
    @Query(" SELECT o FROM Sobject o LEFT JOIN o.statusChanges sh LEFT JOIN o.actions a WHERE o.id = :id ")
    public Optional<Sobject> findById11(@Param("id") Long id);
}

Контроллер:

package ...
import ...

@Controller
public class ObjectsController {

    @Autowired
    private SobjectRepo objectRepo;

    @GetMapping("/objects/object/{id}")
    public String getObject(@PathVariable(value = "id") long id, Model model) {
        
        Optional<Sobject> oObject = objectRepo.findById11(id);
        model.addAttribute("object", oObject.get());
        return "objects/object";
    }
}

Модель:

package ...
import ...

@Entity
@Table(name="objects")
public class Sobject implements Comparable<Sobject> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    ...
    
    @ElementCollection(targetClass=String.class , fetch=FetchType.LAZY)
    @JoinTable(name="objects_statuses_changes")
    List<String> statusChanges = new ArrayList<String>();
    
    @OneToMany(mappedBy="object", fetch=FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
    List<Action> actions = new ArrayList<Action>();

    ...
}

На странице при помощи thymeleaf я вывожу и actions, и statusChanges. Получаю:

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/objects/object.html]"
...
Caused by: org.attoparser.ParseException: failed to lazily initialize a collection of role: com.stst.head.models.Sobject.statusChanges, could not initialize proxy - no Session
...
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.stst.head.models.Sobject.statusChanges, could not initialize proxy - no Session
...
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.stst.head.models.Sobject.statusChanges, could not initialize proxy - no Session
...

Я неправильно написал JOIN? Или для использования @Query нужно что-то большее, чем просто написать аннотацию?


Ответы (1 шт):

Автор решения: MishaBucha

Поставьте fetch=FetchType.EAGER или пропишите в applacation.properties spring.jpa.properties.hibernate.jdbc.enable_lazy_load_no_trans=true

→ Ссылка