1.通过openSession方法获取session,具体操作为:
//
测试
openSession方法获取session对象
@Test
public void test1() {
Configuration cfg = new Configuration().configure();//
通过它来获得配置文件
ServiceRegistry serviceRegistry = new //
ServiceRegistry 是 Service 的注册表, 它为Service提供了一个统一的加载 / 初始化 / 存放 / 获取机制.
ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Student stu = new Student(1, "王五", "中国人民大学");
session.save(stu);
transaction.commit();
session.close();
sessionFactory.close();
}
2.通过getCurrentSession() 方法获取session对象:
//测试getCurrentSession方法获取session对象
@Test
public void test2() {
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
//使用getCurrentSession()方法获取session必须在配置文件中添加相关的属性。
Session session = sessionFactory.getCurrentSession();
if(session != null) {
System.out.println("session创建成功.");
}else {
System.out.println("session创建失败!!!");
}
session.close();
sessionFactory.close();
}
用到的配置文件为hibernate.cfg.xml:
<session-factory>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.
MySQL
.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/testhibernate?useUnicode=true&characterEncoding=UTF-8</property>
<!-- 方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 三个常用属性 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 前缀
<property name="hibernate.default_schema">hibernate</property> -->
<property name="hbm2ddl.auto">create</property>
<!-- 使用getCurrentSession() 方法获取session时必须在配置文件中添加此属性. -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 映射文件,此处不用 -->
<mapping resource="cn/com/gjw/model/Student.hbm.xml"/>
</session-factory>