Hibernate初始化创建SessionFactory,Session,关闭SessonFactory,session
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相关推荐
- [Hibernate系列—] 2. 创建SessionFactory 与 Session
Configuration 对象创建 要创建SessionFactory , 首先要创建Configuration 对象. 这个对象就是去读取hibernate 的一些配置信息. 默认状况下, hib ...
- 为什么要用Hibernate框架? 把SessionFactory,Session,Transcational封装成包含crud的工具类并且处理了事务,那不是用不着spring了?...
既然用Hibernate框架访问管理持久层,那为何又提到用Spring来管理以及整合Hibernate呢?把SessionFactory,Session,Transcational封装成包含crud的 ...
- 四、Hibernate框架的API (三)-- Session对象
一.Session对象 1.Hibernate最重要的对象,只用使用hibernate与数据库操作,都用到这个对象2.该对象维护了一个Connection对象.代表了与数据库连接的会话.3.该对象实质 ...
- 2021-06-04 Java对象在Hibernate下的4种状态和Session相关方法以及对象识别
注:集成开发环境软件:MyEclipse(2017破解版)和mySQL(MySQL Server 8.0) 一.Query(查询) (1)Query(查询)接口允许你在数据库上执行查询并控制查询如何执 ...
- Hibernate之代码创建SessionFactory
hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibe ...
- Hibernate 异常org.hibernate.LazyInitializationException: could not initialize proxy - no Session
最近代写毕业设计中小网站,SSH架构,三年没搞过这个,忘记了,今天遇到这个问题就记录下: 错误页面提示 could not initialize proxy - no Session 控制台 org. ...
- 解决Hibernate:could not initialize proxy - no Session
/*************************************************************************************************** ...
- TensorFlow c++ SessionFactory注册与No session factory registered错误
TensorFlow c++ SessionFactory注册与No session factory registered错误 背景 近期我们在服务器上使用TensorFlow来进行推理,作为云推理服 ...
- 关于关闭浏览器Session就丢失的讨论
对于做web开发的人,不管用ASP.NET JAVA还是其他,都会经常用Session来保存一些信息.而对于Session消失的问题,初学者都会有个误区,认为关闭浏览器,Session值就丢失了.包括 ...
最新文章
- WebBrowser
- 大学生就业重心能否“二线城市化”?
- ROS探索总结(十三)(十四)(十五)——导航与定位框架 move_base(路径规划) amcl(导航与定位)
- MVC Razor 语法(转)
- Qt Creator在外部应用程序上运行Valgrind工具
- 微信支付,银联支付,支付宝支付——三大支付总结
- leetcode-6-Z字形变换
- 【转】使用CSS 禁止文本选择
- Visual C++编译选项
- mysql多线程访问总结
- c#用友U8API开发之环境搭建(1)
- 字节跳动小程序平台审核常见被拒情形
- 一键圣诞帽 html5源码,HTML5在线教程之微信小程序“圣诞帽”的实现思路详解
- 有关Android插件化的一些总结思考,html5在移动端开发优势更明显
- Lazy Binomial Heaps
- vtk教程第六章 基础算法
- 记一次系统重装后电脑的优化设置
- div获得/失去焦点
- 2022CCPC桂林站感想与反思
- YOLO-V5 算法和代码解析系列 —— 学习路线规划综述
热门文章
- Linux增加Qt模块,Qtcreator:linux系统下安装qtserialport模块
- java编程xml_XML Java编程
- Java三层结构的概念_Java中的mvc和三层结构究竟是什么关系
- shared_ptr,weak_ptr使用最广范的智能指针
- php作业制作htm,PHP作业-HTML-2020-09-28
- 手机黑圆点怎么打_手机能「打快板」是怎么回事?浅谈手机的光学防抖
- qt高亮快捷键_Qt高级——QtCreator常用快捷键
- r生成html文件,从R中的许多html文件创建一个语料库
- openerp mysql_Odoo字段(Fields)总结-至2020全
- java Paths