hibernate连接数据库的工具类(SessionFactoryUtil)

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_a</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 显示sql语句 -->
        <property name="show_sql" >true</property>
        <!-- 格式化sql语句 -->
        <property name="format_sql" >true</property>
        
        <mapping resource="com/liuyongqi/MavenHibernateDemo2/entity/News.hbm.xml"/>
        <mapping resource="com/liuyongqi/MavenHibernateDemo2/entity/Student.hbm.xml"/>        
    </session-factory>
</hibernate-configuration>

SessionFactoryUtil工具类

package com.liuyongqi.MavenHibernateDemo2.util;

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

/**
 * 提供了开启和关闭session的方法
 * @author Administrator
 * @data   2018年8月1日
 * @time   下午3:32:56
 */
public class SessionFactoryUtil {
	//ThreadLocal为每个线程提供一个单独的存储空间
	private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
	
	//私有化静态变量,静态变量只实例化一次
	private static SessionFactory sessionFactory;
	//实例化一次sessionFactory
	static {
		Configuration configure = new Configuration().configure();
		sessionFactory=configure.buildSessionFactory();
	}
	//私有化构造方法
	private SessionFactoryUtil() {
		
	}
	//打开session的方法
	public static Session openSession() {
		//从ThreadLocal中拿取一个session
		Session session = threadLocal.get();
		if(null==session) {
			//sessionFactory打开一个session
			session=sessionFactory.openSession();
			//把session又放入ThreadLocal中
			threadLocal.set(session);
		}
		return session;
	}
	
	//关闭资源
	public static void closeSession() {
		//从ThreadLocal中拿取一个session
		Session session = threadLocal.get();
		if(null==session) {
			if(session.isOpen()) {
				//关闭session
				session.close();
			}
			threadLocal.set(null);
		}		
	}
	
	public static void main(String[] args) {
		Session session = openSession();
		System.out.println(session);
		System.out.println("ok");
	}
	
}

敬请期待下一次我的文章

猜你喜欢

转载自blog.csdn.net/LYQ2332826438/article/details/81333875
今日推荐