Hibernate初始化创建SessionFactory,Session,关闭SessonFactory,session

1.hibernate.cfg.xml

 <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect</property> <!-- 数据库方言 -->
<property name="connection.url">
jdbc:mysql://localhost:3306/db_examsystem</property><!-- 数据库连接URL -->
<property name="connection.username">root</property> <!-- 数据库用户名 -->
<property name="connection.password">123456</property> <!-- 数据库用户密码 -->
<property name="connection.driver_class"> <!-- 数据库驱动类 -->
com.mysql.jdbc.Driver</property>
<mapping resource="com/sanqing/po/Student.hbm.xml"/>
<mapping resource="com/sanqing/po/Teacher.hbm.xml"/>
<mapping resource="com/sanqing/po/Subject.hbm.xml"/>
</session-factory>
</hibernate-configuration>

2.hibernateSessionFactory类

 package com.sanqing.hibernate;

 import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.junit.Test; public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION
= "/hibernate.cfg.xml"; //指定配置文件路径
private static final ThreadLocal<Session> threadLocal
= new ThreadLocal<Session>(); //定义ThreadLocal对象
private static Configuration configuration
= new Configuration(); //定义Configuration对象
private static org.hibernate.SessionFactory sessionFactory;//定义SessionFactory对象
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);//读取配置文件
sessionFactory =
configuration.buildSessionFactory();//根据配置文件创建SessionFactory对象
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();//从ThreadLocal对象中获得Session对象
if (session == null || !session.isOpen()) {//判断获得的Session对象是否为空或者未打开
if (sessionFactory == null) {//如果没有创建SessionFactory对象,则首先创建
// rebuildSessionFactory();
}
//如果SessionFactory对象不为空,则调用其openSession方法创建Session对象
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);//在ThreadLocal对象中保存该Session对象
}
return session;
}
// public static void rebuildSessionFactory() {
// try {
// configuration.configure(configFile);//读取配置文件
// sessionFactory =
// configuration.buildSessionFactory();//根据配置文件创建sessionFactory对象
// } catch (Exception e) {
// System.err
// .println("%%%% Error Creating SessionFactory %%%%");
// e.printStackTrace();
// }
// }
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();//从ThreadLocal对象中获得Session对象
threadLocal.set(null);//将当前线程Session对象从ThreadLocal对象中移除
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {//取得SessionFactory对象
return sessionFactory;
}
public static void setConfigFile(String configFile) {//设置新的配置文件
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {//获得Configuration对象
return configuration;
}
}

3.student

 package com.sanqing.po;
/*
* 学生表,保存学生编号,系统密码
*/
public class Student {
private String studentID;
private String password;
private String studentName;
private Integer result;
private String sclass;
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Integer getResult() {
return result;
}
public void setResult(Integer result) {
this.result = result;
}
public String getSclass() {
return sclass;
}
public void setSclass(String sclass) {
this.sclass = sclass;
}
}

4.student.hbm.xml

 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sanqing.po.Student" table="tb_student"><!-- 每个class对应一个持久化对象 -->
<id name="studentID" type="string"><!-- id元素用来定义主键标识,并指定主键生成策略 -->
<generator class="assigned"></generator>
</id>
<property name="password" type="string"></property><!-- 映射password属性 -->
<property name="studentName" type="string"></property><!-- 映射studentName属性 -->
<property name="result" type="int"></property><!-- 映射result属性 -->
<property name="sclass" type="string"></property><!-- 映射sclass属性 -->
</class>
</hibernate-mapping>

5.studentDao

 package com.sanqing.dao;

 import java.util.List;

 import com.sanqing.po.Student;

 public interface StudentDAO {
public Student findByStudentID(String studentID);//查询方法,根据学生ID查询
public void updateStudent(Student student);//更新学生信息
public List<Student> findByStudentName(String studentName);//根据学生姓名查找学生
public List<Student> findByStudentClass(String sclass);//根据班级查找学生
}

6.studentDaoImpl

 package com.sanqing.dao;

 import java.util.Iterator;
import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction; import com.sanqing.hibernate.HibernateSessionFactory;
import com.sanqing.po.Student;
import com.sanqing.po.Subject; public class StudentDAOImpl implements StudentDAO{
public Student findByStudentID(String studentID) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Student student = (Student) session.get(Student.class, studentID);
HibernateSessionFactory.closeSession();//关闭Session对象
return student;
} public void updateStudent(Student student) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Transaction transaction = null;//声明一个事务对象
try{
transaction = session.beginTransaction();//开启事务
session.update(student);//更新学生信息
transaction.commit();//提交事务
}catch(Exception ex) {
ex.printStackTrace();
transaction.rollback();//事务回滚
}
HibernateSessionFactory.closeSession();//关闭Session对象
} public List<Student> findByStudentName(String studentName) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Query query = session.createQuery("from Student as stu where stu.studentName = ?");
query.setString(0, studentName);
List list = query.list(); //查询结果保存到list中
HibernateSessionFactory.closeSession(); //关闭Session对象
return list;
} public List<Student> findByStudentClass(String sclass) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Query query = session.createQuery("from Student as stu where stu.sclass = ?");
query.setString(0, sclass);
List list = query.list(); //查询结果保存到list中
HibernateSessionFactory.closeSession(); //关闭Session对象
return list;
}
}
 package com.sanqing.dao;

 import java.util.Iterator;
import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction; import com.sanqing.hibernate.HibernateSessionFactory;
import com.sanqing.po.Student;
import com.sanqing.po.Subject; public class StudentDAOImpl implements StudentDAO{
public Student findByStudentID(String studentID) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Student student = (Student) session.get(Student.class, studentID);
HibernateSessionFactory.closeSession();//关闭Session对象
return student;
} public void updateStudent(Student student) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Transaction transaction = null;//声明一个事务对象
try{
transaction = session.beginTransaction();//开启事务
session.update(student);//更新学生信息
transaction.commit();//提交事务
}catch(Exception ex) {
ex.printStackTrace();
transaction.rollback();//事务回滚
}
HibernateSessionFactory.closeSession();//关闭Session对象
} public List<Student> findByStudentName(String studentName) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Query query = session.createQuery("from Student as stu where stu.studentName = ?");
query.setString(0, studentName);
List list = query.list(); //查询结果保存到list中
HibernateSessionFactory.closeSession(); //关闭Session对象
return list;
} public List<Student> findByStudentClass(String sclass) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Query query = session.createQuery("from Student as stu where stu.sclass = ?");
query.setString(0, sclass);
List list = query.list(); //查询结果保存到list中
HibernateSessionFactory.closeSession(); //关闭Session对象
return list;
}
}
上一篇:Azkaban(三)Azkaban的使用


下一篇:Jmeter(二十六) - 从入门到精通 - 搭建开源论坛JForum(详解教程)