在Hibernate中初始化所有延迟加载的集合

3

我已经尝试了许多解决方案来解决我面临的问题,但我仍然不清楚。

我正在使用Hibernate 4。

我的实体中有父子关系。默认情况下,我在父实体中为所有集合使用了延迟加载。然而,在某些情况下,我需要加载整个对象图。在这种情况下,我想强制Hibernate加载所有集合。我知道通过使用criteria.setFetchMode("collectionName",FetchMode.JOIN),我可以加载特定的集合。然而,如果我尝试对多个集合执行此操作,我会得到org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

以下是我的代码:

实体

忽略一些字段和getter和setter方法

public class Employee {
    @Id
    @GeneratedValue
    @Column(name = "EmployeeId")
    private long id;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @Fetch(FetchMode.SELECT)
    @JoinColumn(name = "EmployeeId")
    @LazyCollection(LazyCollectionOption.TRUE)
    private List<EmployeeAddress> employeeAddresses;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @Fetch(FetchMode.SELECT)
    @JoinColumn(name = "EmployeeId")
    @LazyCollection(LazyCollectionOption.TRUE)
    private List<EmployeeLanguage> employeeLanguages;

}

HibernateUtil

public HibernateUtil{

    public TEntity findById(Class<TEntity> clazz, long id) {
            Session session = sessionFactory.getCurrentSession();
            Criteria criteria = session.createCriteria(clazz);
            criteria.add(Restrictions.eq("id",id));
            ClassMetadata metadata = sessionFactory.getClassMetadata(clazz);

            String[] propertyNamesArray = metadata.getPropertyNames();
            for(int i=0;i<propertyNamesArray.length;i++){
                criteria.setFetchMode(propertyNamesArray[i], FetchMode.JOIN);
            }
            return (TEntity)criteria.uniqueResult();
        }
}

服务

private void getAllEmployee(Employee employee) {
         //invoke the findAll method of hibernateutil
}

我希望在findAll()方法中使用eager-loading来加载Employee的所有集合。请告诉我如何实现。

在HibernateUtil中使用FetchType.SELECT时添加堆栈跟踪

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.myapp.hr.entity.Employee.employeeAddresses, could not initialize proxy - no Session
    org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
    org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
    org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
    org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
    org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266)
    java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:1099)
    java.util.Collections$UnmodifiableCollection.iterator(Collections.java:1098)
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:90)
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
    org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:253)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:207)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
    org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:125)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:439)
    org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:178)

你能否简单地将获取模式更改为急切,而不是懒惰的吗? - Software Engineer
不,除了这种情况,我需要它是懒惰的。 - Yadu Krishnan
2个回答

3

我在另一个答案的评论中提到过这一点,但它与本题不同,我不想通过编辑原始答案来失去Gimby的见解。

您可以使用反射查找带有@LazyCollection注释的字段,并对其调用Hibernate.initialize()。 它应该是这样的:

    public static <T> void forceLoadLazyCollections(Class<T> tClass, T entity) {
        if (entity == null) {
            return;
        }
        for (Field field : tClass.getDeclaredFields()) {
            LazyCollection annotation = field.getAnnotation(LazyCollection.class);
            if (annotation != null) {
                try {
                    field.setAccessible(true);
                    Hibernate.initialize(field.get(entity));
                } catch (IllegalAccessException e) {
                    log.warning("Unable to force initialize field: " + field.getName());
                }
            }
        }
    }

1
将您的获取模式更改为FetchMode.SELECT。使用联接来拉取集合只能应用于一个集合/表,因为它会导致大量重复数据通过网络传输。使用单独的选择来拉取集合可以随意使用。

如果我使用FetchMode.Select,我会得到LazyInitializationException。它没有强制加载延迟加载的集合 :( - Yadu Krishnan
调用Hibernate.initialize()来初始化检索到的实体中的每个集合是否可接受? - Erik Gillespie
1
为什么这会让人感到惊讶呢?FetchMode的javadoc清楚地说明:“表示关联提取策略。这与Criteria API一起使用,用于指定运行时提取策略。”因此,它显然只影响Criteria API。告诉Hibernate“是的,使用LAZY提取...但仍然EAGER提取它们!”这将非常矛盾。Lazy并不真正意味着数据如何被提取,它意味着数据被提取的时间:lazy = 尽可能晚。 - Gimby
1
实际上,我认为:在这种情况下,您不希望这是自动映射,而应该是一个DAO方法,在适当的时间获取相关数据。 - Gimby
1
@Gimby,我面临的问题是,我的某些实体中有超过10个集合。当我需要一次性加载整个对象时,我必须为每个集合执行Hibernate.initialize("collection1")。我想避免在每个DAO层中都这样做,而是公开一个通用方法来EAGER加载整个实体。这不是一个正确的方法吗? - Yadu Krishnan
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接