单例模式的SessionFactory与getCurrentSession()的使用

getCurrentSession()获得的session的好处。
(1)currentSession和当前线程绑定。
(2)currentSession在事务提交后自动关闭。

需要在 hibernate.cfg.xml 中添加的配置

<property name="hibernate.current_session_context_class">thread</property>

创建类 HibernateUtil.java实现单例模式的SessionFactory。

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static SessionFactory factory;

    // 静态初始化块,加载配置信息,获取SessionFactory
    static {
        // 读取hibernate.cfg.xml文件
        Configuration cfg = new Configuration().configure();
        // 建立SessionFactory
        factory = cfg.buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return factory;
    }
}

使用getCurrentSession()获得session

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import demo.entity.User;

public class Test {
    public static void main(String[] args) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        //getCurrentSession()生成的Session不需要手动关闭,会在事务提交后自动关闭。
        Session session = factory.getCurrentSession();
        User user = new User();
        user.setUsername("qqqqq");
        user.setPassword("qqqqq");
        user.setNickname("name1");
        Transaction transaction = null;
        try {
            // 得到事务对象
            transaction = session.beginTransaction();
            // 添加操作
            session.save(user);
            //session.delete(user);//删除操作
            //User tmp = session.find(User.class, 1);//查找操作
            //session.update(user);//更新操作
            // 提交事务
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                // 事务回滚
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35224639/article/details/80298718
今日推荐