Struts2+Hibernate4整合(二)
来源:互联网 发布:uploadify java demo 编辑:程序博客网 时间:2024/06/01 20:42
一、核心接口:
Session接口
此Session不是JSP中的HttpSession,而是Hibernate中数据连接和事务管理之间的一个中间接口,是持久化操作的基础,提供了save(),update()、delete()等方法SessionFactory接口
负责初始化Hibernate,创建Session实例,它保存了当前数据库配置的所有映射关系Transaction
负责事务的相关操作
二、Hibernate运行过程
- 通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件
- 由hibernate.cfg.xml中的
三、调用Hibernate API对数据库进行操作
1、首先需要创建Hibernate的Session工厂,这是一个单例类,在后续的操作中需要用到这个Session工厂类
public class HibernateSessionFactory { private static SessionFactory sessionFactory;//会话工厂属性 private HibernateSessionFactory(){ } //获得会话工厂对象 public static SessionFactory getSessionFactory(){ if(sessionFactory==null){ //创建配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); sessionFactory = config.buildSessionFactory(serviceRegistry); return sessionFactory; }else{ return sessionFactory; } }}
2、使用Session进行对数据库增删改查的操作,这里的hql语句与sql语句不同,from Student,这里的Student一定是类名,而非表名
基本结构
public 返回值 方法名() { 返回对象声明 Transaction tx = null; String hql = null; try { Session session = HibernateSessionFactory.getSessionFactory() .getCurrentSession(); tx = session.beginTransaction(); hql = "hql语句"; Query query = session.createQuery(hql); Session操作语句 tx.commit(); } catch (Exception ex) { ex.printStackTrace(); tx.commit(); } finally { if (tx != null) tx = null; } return list; }
删除操作
不需要用到hql语句,一般需要id即可,将基本结构中的Session操作语句改为下面的即可
Student s = (Student) session.get(Student.class, sid); session.delete(s);
获取列表操作
hql = "from Student"; Query query = session.createQuery(hql); list = query.list();
添加操作
其中一般要为其在数据库表中设置一个新的id,需要自己写一个私有方法getNewSid()来获得
student.setSid(getNewSid());session.save(student);
更新操作
session.update(student);
0 0
- Struts2+Hibernate4整合(二)
- struts2.3+hibernate4.2+spring3.2整合 (二)
- Struts2+Spring4+Hibernate4整合系列--(二) 原理讲解
- Struts2.x+Spring3.x+Hibernate4.x 整合(二)Struts+Spring 整合
- struts2、spring4、hibernate4(ssh)整合案例
- struts2+spring3+hibernate4整合
- spring3+Hibernate4+struts2整合
- Struts2+Hibernate4+Spring4整合
- Struts2+Hibernate4整合
- spring4+hibernate4+struts2整合
- Spring4 整合Hibernate4,Struts2
- spring3.1+struts2+hibernate4整合
- Struts2+Spring3+Hibernate4+Maven整合
- struts2+hibernate4+spring4整合步骤
- Struts2+Spring4+Hibernate4整合系列--(一) 概述
- Struts2+Spring4+Hibernate4整合系列--(三) 环境准备
- Struts2+Spring4+Hibernate4整合系列--(四)StepByStep1
- Struts2+Spring4+Hibernate4整合系列--(四)StepByStep2
- JavaScript学习之路11_Generator
- Synopsys PrimeTime 功耗分析
- 写代码的最高境界----就是不写代码
- 深拷贝和浅拷贝的理解
- 排列(permutation):用1,2,3,...,9组成3个三位数abc, def和ghi,每个数字恰好使用一次,要求abc:def:ghi = 1:2:3。输出所有解。提示:不必太动脑筋。
- Struts2+Hibernate4整合(二)
- Android拖拽的ExpandableListView
- POJ 1442 Black Box
- 默认构造函数和默认复制构造函数
- JS正则表达式+---贪婪和非贪婪模式学习总结
- 关于VS2013中的字体颜色
- UI基础-UITableView 编辑
- 浅析AFNetWorking
- 安卓驱动、HAL、JNI与java