您的位置:首页 > 运维架构

hibernate获取session的两种方式分别是openSession() 方法和getCurrentSession() 方法。

2017-04-26 10:47 459 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐