尝试使用 size() 方法加载集合时如何解决 LazyInitializationException?

How to solve LazyInitializationException when you try to load collection with size() method?

环境:

CourseService(EJB) 通过 Id 使用 findById() 方法找到课程,然后尝试使用 size() 函数延迟加载 courseModuls,但我得到 LazyInizialitzationException。 这是从 Jboss 5.2 迁移过来的,它工作正常,但是在 Jboss7.2 中我得到了这个错误。

知道那是什么吗?

课程服务

@Stateless
@Local
@RolesAllowed(RolConstants.EVERYONE)
public class CourseService extends BusinessService<Course> implements CourseServiceable {
...
    @Override
    @PermitAll
    public Course findByIdPartial(Object id) throws AppException {
        Course Course = findById(id);
        Course.getCourseModuls().size();

        return Course;
    }
...

CourseBean

@Named
@ViewScoped
public class CourseBean extends LazyBean<Course> implements Serializable {
...
    public void load() {
        try {
            selected = service.findByIdPartial(selected.getId());
        } catch (AppException e) {
            log.error("CourseBean.load()", e);
            faceMessage.error("error.load", e);
        }
    }
...

错误

12:15:19,160 SEVERE [org.primefaces.application.exceptionhandler.PrimeExceptionHandler] (default task-1) failed to lazily initialize a collection of role: es.caib.forma.business.form.entity.Course.courseModuls, could not initialize proxy - no Session: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: es.caib.forma.business.form.entity.Course.courseModuls, could not initialize proxy - no Session
    at org.hibernate@5.3.7.Final-redhat-00001//org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:597)
    at org.hibernate@5.3.7.Final-redhat-00001//org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:216)
    at org.hibernate@5.3.7.Final-redhat-00001//org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:160)
    at org.hibernate@5.3.7.Final-redhat-00001//org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:287)
    at deployment.fora2.ear//es.caib.fora.business.formacio.boundary.CourseService.findByIdPartial(CourseService.java:337)
    at deployment.form2.ear.forma-front.war//es.caib.forma.presentation.front.form.CourseBean.load(CourseBean.java:104)

课程

@Entity
@Table(name = "COURSE")
public class Course implements Serializable {
...
   @OneToMany(mappedBy = "curs", cascade = { CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH })
    private List<CursModul> cursModuls;
...

您应该在方法findByIdPartials()中添加注解@Transactional,因为当方法findById() return 过程结束时,事务也会结束。 您可以在那里找到有关此注释的更多信息:link 正确代码如下:

@Override
@PermitAll
@Transactional
public Course findByIdPartial(Object id) throws AppException {
    Course Course = findById(id);
    Course.getCourseModuls().size();

    return Course;
}