1.hibernate.cfg.xml

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

2.hibernateSessionFactory类

  1. package com.sanqing.hibernate;
  2.  
  3. import org.hibernate.HibernateException;
  4. import org.hibernate.Session;
  5. import org.hibernate.cfg.Configuration;
  6. import org.junit.Test;
  7.  
  8. public class HibernateSessionFactory {
  9. private static String CONFIG_FILE_LOCATION
  10. = "/hibernate.cfg.xml"; //指定配置文件路径
  11. private static final ThreadLocal<Session> threadLocal
  12. = new ThreadLocal<Session>(); //定义ThreadLocal对象
  13. private static Configuration configuration
  14. = new Configuration(); //定义Configuration对象
  15. private static org.hibernate.SessionFactory sessionFactory;//定义SessionFactory对象
  16. private static String configFile = CONFIG_FILE_LOCATION;
  17. static {
  18. try {
  19. configuration.configure(configFile);//读取配置文件
  20. sessionFactory =
  21. configuration.buildSessionFactory();//根据配置文件创建SessionFactory对象
  22. } catch (Exception e) {
  23. System.err
  24. .println("%%%% Error Creating SessionFactory %%%%");
  25. e.printStackTrace();
  26. }
  27. }
  28. private HibernateSessionFactory() {
  29. }
  30. public static Session getSession() throws HibernateException {
  31. Session session = (Session) threadLocal.get();//从ThreadLocal对象中获得Session对象
  32. if (session == null || !session.isOpen()) {//判断获得的Session对象是否为空或者未打开
  33. if (sessionFactory == null) {//如果没有创建SessionFactory对象,则首先创建
  34. // rebuildSessionFactory();
  35. }
  36. //如果SessionFactory对象不为空,则调用其openSession方法创建Session对象
  37. session = (sessionFactory != null) ? sessionFactory.openSession(): null;
  38. threadLocal.set(session);//在ThreadLocal对象中保存该Session对象
  39. }
  40. return session;
  41. }
  42. // public static void rebuildSessionFactory() {
  43. // try {
  44. // configuration.configure(configFile);//读取配置文件
  45. // sessionFactory =
  46. // configuration.buildSessionFactory();//根据配置文件创建sessionFactory对象
  47. // } catch (Exception e) {
  48. // System.err
  49. // .println("%%%% Error Creating SessionFactory %%%%");
  50. // e.printStackTrace();
  51. // }
  52. // }
  53. public static void closeSession() throws HibernateException {
  54. Session session = (Session) threadLocal.get();//从ThreadLocal对象中获得Session对象
  55. threadLocal.set(null);//将当前线程Session对象从ThreadLocal对象中移除
  56. if (session != null) {
  57. session.close();
  58. }
  59. }
  60. public static org.hibernate.SessionFactory getSessionFactory() {//取得SessionFactory对象
  61. return sessionFactory;
  62. }
  63. public static void setConfigFile(String configFile) {//设置新的配置文件
  64. HibernateSessionFactory.configFile = configFile;
  65. sessionFactory = null;
  66. }
  67. public static Configuration getConfiguration() {//获得Configuration对象
  68. return configuration;
  69. }
  70. }

3.student

  1. package com.sanqing.po;
  2. /*
  3. * 学生表,保存学生编号,系统密码
  4. */
  5. public class Student {
  6. private String studentID;
  7. private String password;
  8. private String studentName;
  9. private Integer result;
  10. private String sclass;
  11. public String getStudentID() {
  12. return studentID;
  13. }
  14. public void setStudentID(String studentID) {
  15. this.studentID = studentID;
  16. }
  17. public String getPassword() {
  18. return password;
  19. }
  20. public void setPassword(String password) {
  21. this.password = password;
  22. }
  23. public String getStudentName() {
  24. return studentName;
  25. }
  26. public void setStudentName(String studentName) {
  27. this.studentName = studentName;
  28. }
  29. public Integer getResult() {
  30. return result;
  31. }
  32. public void setResult(Integer result) {
  33. this.result = result;
  34. }
  35. public String getSclass() {
  36. return sclass;
  37. }
  38. public void setSclass(String sclass) {
  39. this.sclass = sclass;
  40. }
  41. }

4.student.hbm.xml

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

5.studentDao

  1. package com.sanqing.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.sanqing.po.Student;
  6.  
  7. public interface StudentDAO {
  8. public Student findByStudentID(String studentID);//查询方法,根据学生ID查询
  9. public void updateStudent(Student student);//更新学生信息
  10. public List<Student> findByStudentName(String studentName);//根据学生姓名查找学生
  11. public List<Student> findByStudentClass(String sclass);//根据班级查找学生
  12. }

6.studentDaoImpl

  1. package com.sanqing.dao;
  2.  
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6. import org.hibernate.Query;
  7. import org.hibernate.Session;
  8. import org.hibernate.Transaction;
  9.  
  10. import com.sanqing.hibernate.HibernateSessionFactory;
  11. import com.sanqing.po.Student;
  12. import com.sanqing.po.Subject;
  13.  
  14. public class StudentDAOImpl implements StudentDAO{
  15. public Student findByStudentID(String studentID) {
  16. Session session = HibernateSessionFactory.getSession();//获得Session对象
  17. Student student = (Student) session.get(Student.class, studentID);
  18. HibernateSessionFactory.closeSession();//关闭Session对象
  19. return student;
  20. }
  21.  
  22. public void updateStudent(Student student) {
  23. Session session = HibernateSessionFactory.getSession();//获得Session对象
  24. Transaction transaction = null;//声明一个事务对象
  25. try{
  26. transaction = session.beginTransaction();//开启事务
  27. session.update(student);//更新学生信息
  28. transaction.commit();//提交事务
  29. }catch(Exception ex) {
  30. ex.printStackTrace();
  31. transaction.rollback();//事务回滚
  32. }
  33. HibernateSessionFactory.closeSession();//关闭Session对象
  34. }
  35.  
  36. public List<Student> findByStudentName(String studentName) {
  37. Session session = HibernateSessionFactory.getSession();//获得Session对象
  38. Query query = session.createQuery("from Student as stu where stu.studentName = ?");
  39. query.setString(0, studentName);
  40. List list = query.list(); //查询结果保存到list中
  41. HibernateSessionFactory.closeSession(); //关闭Session对象
  42. return list;
  43. }
  44.  
  45. public List<Student> findByStudentClass(String sclass) {
  46. Session session = HibernateSessionFactory.getSession();//获得Session对象
  47. Query query = session.createQuery("from Student as stu where stu.sclass = ?");
  48. query.setString(0, sclass);
  49. List list = query.list(); //查询结果保存到list中
  50. HibernateSessionFactory.closeSession(); //关闭Session对象
  51. return list;
  52. }
  53. }
  1. package com.sanqing.dao;
  2.  
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6. import org.hibernate.Query;
  7. import org.hibernate.Session;
  8. import org.hibernate.Transaction;
  9.  
  10. import com.sanqing.hibernate.HibernateSessionFactory;
  11. import com.sanqing.po.Student;
  12. import com.sanqing.po.Subject;
  13.  
  14. public class StudentDAOImpl implements StudentDAO{
  15. public Student findByStudentID(String studentID) {
  16. Session session = HibernateSessionFactory.getSession();//获得Session对象
  17. Student student = (Student) session.get(Student.class, studentID);
  18. HibernateSessionFactory.closeSession();//关闭Session对象
  19. return student;
  20. }
  21.  
  22. public void updateStudent(Student student) {
  23. Session session = HibernateSessionFactory.getSession();//获得Session对象
  24. Transaction transaction = null;//声明一个事务对象
  25. try{
  26. transaction = session.beginTransaction();//开启事务
  27. session.update(student);//更新学生信息
  28. transaction.commit();//提交事务
  29. }catch(Exception ex) {
  30. ex.printStackTrace();
  31. transaction.rollback();//事务回滚
  32. }
  33. HibernateSessionFactory.closeSession();//关闭Session对象
  34. }
  35.  
  36. public List<Student> findByStudentName(String studentName) {
  37. Session session = HibernateSessionFactory.getSession();//获得Session对象
  38. Query query = session.createQuery("from Student as stu where stu.studentName = ?");
  39. query.setString(0, studentName);
  40. List list = query.list(); //查询结果保存到list中
  41. HibernateSessionFactory.closeSession(); //关闭Session对象
  42. return list;
  43. }
  44.  
  45. public List<Student> findByStudentClass(String sclass) {
  46. Session session = HibernateSessionFactory.getSession();//获得Session对象
  47. Query query = session.createQuery("from Student as stu where stu.sclass = ?");
  48. query.setString(0, sclass);
  49. List list = query.list(); //查询结果保存到list中
  50. HibernateSessionFactory.closeSession(); //关闭Session对象
  51. return list;
  52. }
  53. }

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. Comet OJ - Contest #6 D. 另一道树题 并查集 + 思维 + 计数

    Code: #include <cstdio> #include <algorithm> #include <cstring> #include <vecto ...

  2. docker-compose简介

    一.Docker-Compose简介   Docker-Compose项目是Docker官方的开源项目,负责实现对Docker容器集群的快速编排.   Docker-Compose将所管理的容器分为三 ...

  3. 微信小程序自定义底部导航栏组件+跳转

    微信小程序本来封装有底部导航栏,但对于想自定义样式和方法的开发者来说,这并不是很好. 参考链接:https://github.com/ljybill/miniprogram-utils/tree/ma ...

  4. Miniprofiler在目中使用报 mini-profiler-resources/includes.js 404错误

    原因,没有配置webconfig <system.webServer> <modules> <remove name="FormsAuthentication& ...

  5. SQL语句之-简单查询

       SQL 语句的语法顺序是: SELECT[DISTINCT] FROM WHERE GROUP BY HAVING UNION ORDER BY 一.查询SELECT 1.查询全部列:SELEC ...

  6. [CSP-S模拟测试]:树(树上上升序列+主席树+线段树)

    题目传送门(内部题78) 输入格式 第一行输入两个整数$n,q$,表示节点数和询问数. 第二行输入$n$个整数$w_i$,表示第$i$个点的智商. 第三行至第$n+1$行每行输入两个数$x,y$,表示 ...

  7. 在命令行运行java代码

    因为尝试将运行结果通过管道命令保存,所以尝试在命令行(不借助lde来运行java代码,结果折腾了半天) 仿照的是eclipse创建文件目录的方式 最终解决方法是: #/bin/bash root_di ...

  8. 记一次SQL Server delete语句的优化过程

    今天测试反应问题,性能测试环境一个脚本执行了3个小时没有出结果,期间其他dba已经建立了一些索引但是没有效果. 语句: DELETE T  from License T  WHERE exists ( ...

  9. SqlServer2012 File Table文件表

    SQL Server 2012 提供一种特殊的“文件表”,也称为“FileTable”. FileTable 是一种专用的用户表,它包含存储 FILESTREAM 数据的预定义架构以及文件和目录层次结 ...

  10. requirejs define a module

    https://requirejs.org/docs/api.html#define Define a Module § 1.3 A module is different from a tradit ...