测试hibernate配置是否正确的小工具

public class SessionFactoryUtil {

	static SessionFactory sessionFactory;
	static {
		//得到配置类
		Configuration configure = new Configuration().configure("hibernate.cfg.xml");
		//拿到sessionFactory
		sessionFactory=configure.buildSessionFactory();
	}
	
	public static Session getSession() {
		Session session = sessionFactory.getCurrentSession();
		//用户第一次向服务器拿请求,肯定是没有会话的,做个判断
		//第一次拿请求,是没有会话的,openSession打开一个会话,第二次同一个用户操作数据库的话,session肯定不为空
		//sessionFactory.getCurrentSession()  拿到本地的一个session
		if(session == null) {
			session=sessionFactory.openSession();
		}
		return session;
	}
	
	public static void main(String[] args) {
		Session session =SessionFactoryUtil.getSession();
		session.beginTransaction();
		//isConnected   是否连接
		System.out.println(session.isConnected());
		session.close();
		System.out.println(session.isConnected());
	}
}

猜你喜欢

转载自blog.csdn.net/li_2580/article/details/84554955