openSession和getCurrentSession

在比較openSession和getCurrentSession這兩個方法之前,我們先認識一下這兩個方法。

在進行配置信息管理時,我們一般進行一下簡單步驟:

Configuration cfg = new Configuration(); // 獲得配置信息對象
SessionFactory sf = cfg.configure().buildSessionFactory(); //解析並建立Session工廠

  1. Session session = sf.getCurrentSession(); // 獲得Session

  2. Session session = sf.openSession(); // 打開Session

對於上述的兩個方法,有以下區別:

  1. openSession 從字面上可以看得出來,是打開一個新的session對象,而且每次使用都是打開一個新的session,假如連續使用多次,則獲得的session不是同一個對象,並且使用完需要調用close方法關閉session。

  2. getCurrentSession ,從字面上可以看得出來,是獲取當前上下文一個session對象,當第一次使用此方法時,會自動產生一個session對象,並且連續使用多次時,得到的session都是同一個對象,這就是與openSession的區別之一,簡單而言,getCurrentSession 就是:如果有已經使用的,用舊的,如果沒有,建新的。

注意:在實際開發中,往往使用getCurrentSession多,因爲一般是處理同一個事務(即是使用一個數據庫的情況),所以在一般情況下比較少使用openSession或者說openSession是比較老舊的一套接口了;

對於getCurrentSession 來說,有以下一些特點:

1.用途,界定事務邊界

2.事務提交會自動close,不需要像openSession一樣自己調用close方法關閉session

3.上下文配置(即在hibernate.cfg.xml)中,需要配置:

thread

(需要注意,這裏的current_session_context_class屬性有幾個屬性值:jta 、 thread 常用 , custom、managed 少用 )

a).thread使用connection 單數據庫連接管理事務

b).jta (java transaction api) Java 分佈式事務管理 (多數據庫訪問),jta 由中間件提供(JBoss WebLogic 等, 但是tomcat 不支持)

下面是openSession 和 getCurrentSession 簡單實例的區別 :

1.openSession方式 :


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

import com.hibernate.model.Student; // 注意包路徑

public class StudentTest {
public static void main(String[] args) {

Student s = new Student();
s.setId(1);
s.setName("s1");
s.setAge(1);

Configuration cfg = new Configuration(); // 獲得配置信息對象
SessionFactory sf = cfg.configure().buildSessionFactory(); //解析並建立Session工廠
Session session = sessionFactory.openSession(); // 打開Session

session.beginTransaction(); // 看成一個事務,進行操作
session.save(s); // 會找到 Student 這個類,尋找set方法
session.getTransaction().commit(); // 提交對數據的操作
session.close();

sf.close();

}

}

2.getCurrentSession方式 :

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

import com.hibernate.model.Student; // 注意包路徑

public class StudentTest {
public static void main(String[] args) {

Student s = new Student();
s.setId(1);
s.setName("s1");
s.setAge(1);

Configuration cfg = new Configuration(); // 獲得配置信息對象
SessionFactory sf = cfg.configure().buildSessionFactory(); //解析並建立Session工廠
Session session = sessionFactory.getCurrentSession(); // 打開Session

session.beginTransaction(); // 看成一個事務,進行操作
session.save(s); // 會找到 Student 這個類,尋找set方法
session.getTransaction().commit(); // 提交對數據的操作

sf.close();

}

}

Student 類代碼 :

package com.hibernate.model;

public class Student {
private int id;
private String name;
private int age;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章