【问题标题】:save is not valid without active transaction [duplicate]没有活动交易,保存无效[重复]
【发布时间】:2019-03-05 05:32:37
【问题描述】:

如果我使用 getCurrentSession() 来获取会话并且我没有开始事务并保存会给出异常但是当我使用 openSession() 来获取会话时,那么在相同的场景中程序运行没有任何异常。“hibernate.current_session_context_class”在hibernate配置文件中配置了线程。那么我使用getCurrentSession()和openSession()有什么区别。

Here is the code that gets session using getCurrentSession()-

            public static void main(String ar[])
            {

                SessionFactory sfac=null;

                sfac=new Configuration().configure("hibernateconfig/rs.xml")

                        .buildSessionFactory();

                try {

                Session session=sfac.getCurrentSession();
                Student stu=new Student();
                stu.setFirstName("abc23");
                stu.setLastName("xyz");
                System.out.println("-------------"+stu);
                session.save(stu);

                }
                catch(Exception e)
                {
                    System.out.println(e);
                }

            }

output-

-------------Student [id=0, firstName=abc23, lastName=xyz]
org.hibernate.HibernateException: save is not valid without active transaction


Here is the code that gets session using openSession()-

        public static void main(String ar[])
        {

            SessionFactory sfac=null;

            sfac=new Configuration().configure("hibernateconfig/rs.xml")

                    .buildSessionFactory();

            try {

            Session session=sfac.openSession();
            Student stu=new Student();
            stu.setFirstName("abc23");
            stu.setLastName("xyz");
            System.out.println("-------------"+stu);
            session.save(stu);

            }
            catch(Exception e)
            {
                System.out.println(e);
            }

        }


output-

-------------Student [id=0, firstName=abc23, lastName=xyz]
Hibernate: 
    insert 
    into
        student
        (firstName, lastName) 
    values
        (?, ?)

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    openSession():
    当您调用 SessionFactory.openSession() 时,它总是会创建新的 Session 对象并将其提供给您。您需要显式刷新和关闭这些会话对象。由于会话对象不是线程安全的,因此您需要在多线程环境中为每个请求创建一个会话对象,在 Web 应用程序中也需要为每个请求创建一个会话。

    getCurrentSession():
    当你调用 SessionFactory. getCurrentSession(),它将为您提供处于休眠上下文并由休眠内部管理的会话对象。它绑定到事务范围。当您调用 SessionFactory.getCurrentSession() 时,如果不存在,它会创建一个新会话,否则使用当前休眠上下文中的相同会话。它会在事务结束时自动刷新并关闭会话,因此您无需在外部进行。如果您在单线程环境中使用休眠,则可以使用 getCurrentSession(),因为与每次创建新会话相比,它的性能更快.您需要将以下属性添加到 hibernate.cfg.xml 以使用 getCurrentSession 方法。 线程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-27
      • 2014-08-13
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多