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;
}
}

Hibernate初始化创建SessionFactory,Session,关闭SessonFactory,session的更多相关文章

  1. 为什么要用Hibernate框架? 把SessionFactory,Session,Transcational封装成包含crud的工具类并且处理了事务,那不是用不着spring了?

    既然用Hibernate框架访问管理持久层,那为何又提到用Spring来管理以及整合Hibernate呢?把SessionFactory,Session,Transcational封装成包含crud的 ...

  2. hibernate的延迟加载及其与session关闭的矛盾

    延迟加载就是并不是在读取的时候就把数据加载进来,而是等到使用时再加载. 那么Hibernate是怎么知道用户在什么时候使用数据了呢?又是如何加载数据呢? 其实很简单,它使用了代理机制.返回给用户的并不 ...

  3. 对hibernate的延迟加载如何理解,在实际应用中,延迟加载与session关闭的矛盾是如何处理的?

    对hibernate的延迟加载如何理解,在实际应用中,延迟加载与session关闭的矛盾是如何处理的? 解答:延迟加载就是并不是在读取的时候就把数据加载进来,而是等到使用时再加载.那么Hibernat ...

  4. 如何理解Hibernate的延迟加载机制?在实际应用中,延迟加载与Session关闭的矛盾是如何处理的?

    延迟加载就是并不是在读取的时候就把数据加载进来,而是等到使用时再加载.Hibernate使用了虚拟代理机制实现延迟加载,我们使用Session的load()方法加载数据或者一对多关联映射在使用延迟加载 ...

  5. hibernate在使用getCurrentSession时提示no session found for current thread

    大致错误片段 org.hibernate.HibernateException: No Session found for current thread at org.springframework. ...

  6. 第二节 hibernate session介绍以及session常用方法介绍

    原创地址:http://www.cnblogs.com/binyulan/p/5628579.html Session是java应用程序和hibernate框架之间的一个主要接口.它是从持久化服务中剥 ...

  7. J2EE进阶(九)org.hibernate.LazyInitializationException: could not initialize proxy - no Session

    org.hibernate.LazyInitializationException: could not initialize proxy - no Session 前言 在<many-to-o ...

  8. Hibernate和Spring整合出现懒加载异常:org.hibernate.LazyInitializationException: could not initialize proxy - no Session

    出现问题:  SSH整合项目里,项目目录结构如下: 在EmployeeAction.java的list()方法里将employees的list放入到request的Map中. EmployeeActi ...

  9. Hibernate二次学习二----------session.flush、session.doWork

    目录 1. session 2. session.flush 3. session.doWork 4. 完整代码 5. 总结 © 版权声明:本文为博主原创文章,转载请注明出处 1. session H ...

随机推荐

  1. 牛飞盘队Cow Frisbee Team

    老唐最近迷上了飞盘,约翰想和他一起玩,于是打算从他家的N头奶牛中选出一支队伍. 每只奶牛的能力为整数,第i头奶牛的能力为R i .飞盘队的队员数量不能少于 .大于N. 一支队伍的总能力就是所有队员能力 ...

  2. Kohana Minion cli 学习

    1.E:\html\tproject\framebota\platform\bootstrap.php Kohana::modules(array( 'auth' => MODPATH.'aut ...

  3. 特征点检测算法——FAST角点

    上面的算法如SIFT.SURF提取到的特征也是非常优秀(有较强的不变性),但是时间消耗依然很大,而在一个系统中,特征提取仅仅是一部分,还要进行诸如配准.提纯.融合等后续算法.这使得实时性不好,降系了统 ...

  4. LUOGU P2569 [SCOI2010]股票交易(单调队列优化dp)

    传送门 解题思路 不难想一个\(O(n^3)\)的\(dp\),设\(f_{i,j}\)表示第\(i\)天,手上有\(j\)股的最大收益,因为这个\(dp\)具有单调性,所以\(f_i\)可以贪心的直 ...

  5. 封装类和非封装类比较相同不int和Integer

    A.所有和int(非封装类比较的,只要数值相同就行) B.io3由valueof弄出来的,所以和io1相同 C.io4是new出来的,所以地址不一样,就不相同 D.和A相同

  6. HTML转换PDF及SWF及图片

    一.源码特点        在一些应用场景中,出于某些目的(例如需要对文章内容进行保护,禁止用户真接复制文字内容),不能直接提供HTML的方式进行浏览,那么就需要将文章内容转换为其它的格式如PDF.图 ...

  7. linux让命令或程序在终端后台运行的方法(Ubuntu/Fedora/Centos等一样适用)

    https://segmentfault.com/a/1190000008314935

  8. 高通 8x26 andorid light sensor(TSL258x) 开发【转】

    本文转载自:http://www.voidcn.com/blog/u012296694/article/p-1669831.html 前言 8926平台的sensor架构与之前的平台完全不同,实际上已 ...

  9. elementUI下拉树组件封装

    使用组件:Popover 弹出框.Tree 树形控件 和 input 输入框 用法: 1.新建一个.vue文件,粘贴以下组件封装的代码(完全可以使用) 2.在页面需要使用下拉树的地方调用即可. (1) ...

  10. centos6最小化安装默认没有 NetworkManager服务

    转载Centos6最小化安装中设置网卡默认启动   Centos 6.0版本提供了一个"最小化"(Minimal)安装的选项.这是一个非常好的改进,因为系统中再也不会存在那些不必要 ...