当前位置: 首页 > 知识库问答 >
问题:

冬眠LazyInitializationException:未能延迟初始化角色的集合

柳英资
2023-03-14

我已经对这个错误进行了研究,但仍然找不到合适的解决方案。这是我的代码:

配置:

package com.ambre.pta.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.ambre.pta.dao.MenuDAO;
import com.ambre.pta.dao.MenuDAOImpl;
import com.ambre.pta.dao.RoleDAO;
import com.ambre.pta.dao.RoleDAOImpl;
import com.ambre.pta.dao.UtilisateurDAO;
import com.ambre.pta.dao.UtilisateurDAOImpl;


@Configuration
@ComponentScan("com.ambre.pta")
@EnableTransactionManagement
@PropertySources({
    @PropertySource("classpath:fr/global.properties"),
    @PropertySource("classpath:fr/main.properties"),
    @PropertySource("classpath:fr/admin.properties"),
    @PropertySource("classpath:fr/referentiel.properties")
})
public class ApplicationContextConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() { 
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean(name = "dataSource")
    public DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
        dataSource.setUsername("pta");
        dataSource.setPassword("pta");

        return dataSource;
    }

    @Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);

        sessionBuilder.scanPackages("com.ambre.pta.model");

        return sessionBuilder.buildSessionFactory();

    }

    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {

        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);

        return transactionManager;
    }

    @Autowired
    @Bean(name = "utilisateurDao")
    public UtilisateurDAO getUtilisateurDao(SessionFactory sessionFactory) {
        return new UtilisateurDAOImpl(sessionFactory);
    }

    @Autowired
    @Bean(name = "menuDao")
    public MenuDAO getMenuDao(SessionFactory sessionFactory) {
        return new MenuDAOImpl(sessionFactory);
    }

    @Autowired
    @Bean(name = "roleDao")
    public RoleDAO getRoleDao(SessionFactory sessionFactory) {
        return new RoleDAOImpl(sessionFactory);
    }

}

模型:

    @Entity
    @Table(name = "menu")
    public class Menu {

        @Id
        @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
        private int menu_id;

        private Integer gmnu_code;

        private String menu_lib;

        private Integer menu_ordre;

        private Integer menu_visible;

        private Integer menu_deleted;

        private Integer menu_parent;

        private String menu_controlleur;

        private String menu_navigation;

        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name = "role_menu", joinColumns = { @JoinColumn(name = "menu_id") }, inverseJoinColumns = { @JoinColumn(name = "role_code") })
        private Set<Role> roles = new HashSet<Role>();

        public Menu() {
            super();
        }

        public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_parent, String menu_controlleur, String menu_navigation) {
            super();
            this.gmnu_code = gmnu_code;
            this.menu_lib = menu_lib;
            this.menu_ordre = menu_ordre;
            this.menu_visible = menu_visible;
            this.menu_deleted = menu_deleted;
            this.menu_parent = menu_parent;
            this.menu_controlleur = menu_controlleur;
            this.menu_navigation = menu_navigation;
        }

        public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_parent, String menu_controlleur, String menu_navigation, Set<Role> roles) {
            super();
            this.gmnu_code = gmnu_code;
            this.menu_lib = menu_lib;
            this.menu_ordre = menu_ordre;
            this.menu_visible = menu_visible;
            this.menu_deleted = menu_deleted;
            this.menu_parent = menu_parent;
            this.menu_controlleur = menu_controlleur;
            this.menu_navigation = menu_navigation;
            this.roles = roles;
        }

        // getters and setters....

    }

@Entity
@Table(name = "utilisateur")
public class Utilisateur {

    @Id
    @SequenceGenerator(name="s_utilisateur", sequenceName="s_utilisateur", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_utilisateur")
    private int user_code;

    @Formula(value="user_nom || ' ' || user_prenom")
    private String noms;

    private String user_nom;

    private String user_prenom;

    private String user_login;

    private String user_passwd;

    private String user_email;

    private Integer user_deleted;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "role_user", joinColumns = { @JoinColumn(name = "user_code") }, inverseJoinColumns = { @JoinColumn(name = "role_code") })
    private Set<Role> roles = new HashSet<Role>();

    public Utilisateur() {
        super();
    }

    public Utilisateur(String user_nom, String user_prenom, String user_login, String user_passwd, String user_email, Integer user_deleted) {
        super();
        this.user_nom = user_nom;
        this.user_prenom = user_prenom;
        this.user_login = user_login;
        this.user_passwd = user_passwd;
        this.user_email = user_email;
        this.user_deleted = user_deleted;
    }

    public Utilisateur(String noms, String user_nom, String user_prenom, String user_login, String user_passwd, String user_email, Integer user_deleted, Set<Role> roles) {
        super();
        this.noms = noms;
        this.user_nom = user_nom;
        this.user_prenom = user_prenom;
        this.user_login = user_login;
        this.user_passwd = user_passwd;
        this.user_email = user_email;
        this.user_deleted = user_deleted;
        this.roles = roles;
    }

    // getters and setters...

}

@Entity
@Table(name = "role")
public class Role {

    @Id
    private String role_code;

    private String role_lib;

    @ManyToMany(mappedBy = "roles")
    private Set<Menu> menus = new HashSet<Menu>();

    @ManyToMany(mappedBy = "roles")
    private Set<Utilisateur> users = new HashSet<Utilisateur>();

    public Role() {
        super();
    }

    public Role(String role_lib) {
        super();
        this.role_lib = role_lib;
    }

    public Role(String role_lib, Set<Menu> menus) {
        super();
        this.role_lib = role_lib;
        this.menus = menus;
    }

    // getters and setters...

}

现在在我的控制器中,我调用导致异常的DAO的实现:

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ambre.pta.dao.MenuDAO;
import com.ambre.pta.dao.RoleDAO;
import com.ambre.pta.model.DataTablesTO;
import com.ambre.pta.model.Role;

@Controller
@RequestMapping("/adminrole")
public class AdminRole {

    @Autowired
    private Environment env;

    @Autowired
    private MenuDAO menuDao;

    @Autowired
    private RoleDAO roleDao;

    @RequestMapping(value = "/ajaxDataTableListRoles", produces = "application/json")
    @ResponseBody
    public String ajaxListRole(@RequestParam int draw, @RequestParam int start, @RequestParam int length, 
                               @RequestParam("search[value]") String search, @RequestParam("order[0][column]") int triIdx, @RequestParam("order[0][dir]") String ordreTri) 
     {

        List<Role> rolesDataTable = roleDao.list(start, length, search, triIdx, ordreTri);
        List<Role> rolesAll = roleDao.list();
        DataTablesTO<Role> dt = new DataTablesTO<Role>();
        dt.setData(rolesDataTable);
        dt.setDraw(draw);
        if (search == null || search.equals("")) {
            dt.setRecordsTotal(rolesAll.size());
            dt.setRecordsFiltered(rolesAll.size());
        }
        else {
            dt.setRecordsTotal(rolesDataTable.size());
            dt.setRecordsFiltered(roleDao.nbRoleTotalFiltered(search));
        }

        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.writeValueAsString(dt);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
            return "";
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

}

编辑:

这里是异常堆栈:

org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.ambre.pta.model.Role.menus, could not initialize proxy - no Session (through reference chain: com.ambre.pta.model.DataTablesTO["data"]->java.util.ArrayList[0]->com.ambre.pta.model.Role["menus"])
    at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:218)
    at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:183)
    at org.codehaus.jackson.map.ser.std.SerializerBase.wrapAndThrow(SerializerBase.java:140)
    at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:158)
    at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    at org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:122)
    at org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:71)
    at org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
    at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
    at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
    at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:2575)
    at org.codehaus.jackson.map.ObjectMapper.writeValueAsString(ObjectMapper.java:2097)
    at com.ambre.pta.controller.AdminRole.ajaxListRole(AdminRole.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:285)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.ambre.pta.model.Role.menus, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
    at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:45)
    at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
    at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
    at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
    ... 49 more

那么在这种情况下如何修复延迟加载异常呢?

编辑:

以下是DAO的实现:

public class RoleDAOImpl implements RoleDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public RoleDAOImpl() {
        super();
    }

    public RoleDAOImpl(SessionFactory sessionFactory) {
        super();
        this.sessionFactory = sessionFactory;
    }

    @Override
    @Transactional
    public List<Role> list() {

        @SuppressWarnings("unchecked")
        List<Role> listRole = (List<Role>) sessionFactory.getCurrentSession()
                                                         .createCriteria(Role.class)
                                                         .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
        return listRole;

    }

    @Override
    @Transactional
    public List<Role> list(int start, int length, String search, int triIdx, String ordreTri) {

        String hql = "select r from Role r";

        if (search != null && !search.equals("")) {

            hql = hql.concat(" where ");

            hql = hql.concat(" lower(r.role_lib) like '%").concat(search.toLowerCase()).concat("%'");

        }

        if (ordreTri.equals("asc")) {

            switch (triIdx) {
                case 0:
                    hql = hql.concat(" order by r.role_lib ");
                    break;
                default:
                    hql = hql.concat(" order by r.role_lib ");
                    break;
            }

        } else {

            switch (triIdx) {
                case 0:
                    hql = hql.concat(" order by r.role_lib desc");
                    break;
                default:
                    hql = hql.concat(" order by r.role_lib desc");
                    break;
            }
        }

        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query = query.setFirstResult(start);
        query = query.setMaxResults(length);

        @SuppressWarnings("unchecked")
        List<Role> listRole = (List<Role>) query.list();

        return listRole;

    }

    @Override
    @Transactional
    public int nbRoleTotalFiltered(String search) {

        String hql = "select r from Role r";

        if (search != null && !search.equals("")) {

            hql = hql.concat(" where ");

            hql = hql.concat(" lower(r.role_lib) like '%").concat(search.toLowerCase()).concat("%'");

        }

        Query query = sessionFactory.getCurrentSession().createQuery(hql);

        @SuppressWarnings("unchecked")
        List<Role> listRole = (List<Role>) query.list();

        return listRole.size();

    }

    @Override
    @Transactional
    public Role get(String role_code) {

        return (Role) sessionFactory.getCurrentSession().get(Role.class, role_code);

    }

    @Override
    @Transactional
    public void saveOrUpdate(Role role) {

        Session sess = sessionFactory.getCurrentSession();
        sess.saveOrUpdate(role);

    }

    @Override
    @Transactional
    public void delete(String role_code) {

        sessionFactory.getCurrentSession().delete((Role) sessionFactory.getCurrentSession().get(Role.class, role_code));

    }

}

共有2个答案

鲜于承基
2023-03-14

我用标准的sqlcreateSQLQuery创建了查询,但没有用Hibernate createQuery,dataTable知道索引列!

程俊力
2023-03-14

您需要使用@transactional,LazyInitializationException:无法延迟初始化角色集合,无法初始化代理-没有会话,您需要打开一个事务,让hibernate解析集合的代理,如果有效,请尝试并注释

 类似资料:
  • 嗯,我是Spring的新手。当我试图编译这些代码时,我得到了下面提到的错误。所以请帮我解决这个问题。提前感谢!

  • 我不明白为什么会发生这种情况。根据代码路径,当引发此异常时,我应该在同一线程中并且会话应存在。 有人能告诉我我错过了什么吗? 我有设置 在hibernate.cfg.xml档案里 我在Servlet过滤器中创建了以下代码 在index.xhtml文件中,我有以下调用: 做一些事情 index.xhtml正在使用使用ui include加载menu.xhtml文件的模板。然后,菜单文件会插入menu

  • 问题内容: 我有下一个错误: 我的实体: 我有一个服务班: 我从另一种服务方法调用服务: 但是,当我试图调用这个方法我收到线异常,当我打电话时,也会发生同样的异常上。我已经检查了事务管理器,并且配置正确,并且此步骤中存在事务。另外,我已经检查了关于与此异常相关的stackoverflow的大量答案,但没什么用。 可能是什么原因造成的? 问题答案: 看来模型是一个独立的实体。 尝试合并并在合并实例上

  • 我正在制作一个网站,我试图在其中订购配料。我选择配料并输入其数量,然后单击添加。我重复了几次。然后我进入下一页,在其中我选择了一个供应商。然后我按“订单”。 预计将Nabavka插入数据库并打开一个页面,说明订单成功,但我收到一个异常,告诉我不能懒惰地初始化它。 来自NabavkaController。java: Nabavka.java: 纳米尔尼卡。java: 纳巴夫卡科帕。java: 纳巴夫

  • 问题内容: 我有以下提到的实体类,当我执行我的应用程序时,我得到了以下异常。其他一些类似的问题也不能解决问题。 我该如何解决这个问题? Emp实体 部门实体 DAOImpl 泽西岛RESTful服务 springapplicationContext.xml 问题答案: 我已通过在web.xml中添加以下内容解决了该问题 在这里和这里礼貌 谢谢

  • 问题内容: 在我的spring项目的自定义AuthenticationProvider中,我正在尝试读取已记录用户的权限列表,但是遇到以下错误: 从StackOverflow的此处阅读其他主题,我理解这种情况的发生是由于框架处理此类属性的方式引起的,但是我无法为我的情况找到任何解决方案。有人可以指出我做错了什么,我该怎么做才能解决? 我的Custom AuthenticationProvider的