标签:
Hibernate有了新的版本,部分内容待更新。
package test.hibernate.hbmSessionManage; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.Test; public class App { private static SessionFactory sessionFactory = new Configuration()// .configure("test/hibernate/hbmSessionManage/myhibernate.cfg.xml")// .buildSessionFactory(); /* * 要想使用SessionFactory.getCurrentSession()方法 * 需要在Hibernate主配置文件中配置current_session_context_class项 */ @Test public void testSession() throws Exception { // Session session1 = sessionFactory.getCurrentSession(); // Session session2 = sessionFactory.getCurrentSession(); // Session session1 = sessionFactory.openSession(); // Session session2 = sessionFactory.openSession(); Session session1 = sessionFactory.openSession(); Session session2 = sessionFactory.getCurrentSession(); System.out.println(session1 != null); System.out.println(session1 == session2); } /* * getCurrentSession():指定上下文中(如thread)查找绑 * 定的Session对象,如果有就返回; * 如果没有就创建一个并绑定,然后返回 openSession():只是 * 开启一个新的Session,不会做绑定和查找操作 */ @Test public void testSessionClose() throws Exception { Session session2 = sessionFactory.getCurrentSession(); session2.beginTransaction(); System.out.println("xxxxxxxxxxxxxxxxxxxxxx"); session2.getTransaction().commit(); // session2.close(); } }同名包下
<!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 name="foo"> <!-- 配置数据库信息 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_2015</property> <!-- 可简写为<property name="connection.url">jdbc:mysql:///hibernate_2015</property> --> <property name="connection.username">root</property> <property name="connection.password">686175</property> <!-- 显示生成的sql语句,不写的话默认是false --> <property name="show_sql">true</property> <!-- 当配置为thread时,SessionFactory的getCurrentSession()方法就可以用了 --> <property name="current_session_context_class">thread</property> </session-factory> </hibernate-configuration>
版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请注明出处:http://blog.csdn.net/lindonglian
标签:
原文地址:http://blog.csdn.net/lindonglian/article/details/47000377