繁体   English   中英

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

[英]Initialize all lazy loaded collections in hibernate

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

我正在使用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()方法中急切加载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)

我在其他答案的评论中提到了这一点,但它已经不同了,我不想通过编辑我的原始答案而失去Gimby的见解。

您可以使用反射来查找带​​有@LazyCollection注释的字段,并对@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());
                }
            }
        }
    }

将获取模式更改为FetchMode.SELECT 使用连接来引入集合只能应用于一个集合/表,因为它会导致大量重复数据被拉过线。 可以根据需要使用单独的选择来拉入集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM