· 回顾
· 在Struts中,循环显示List中的数据使用什么标签?
· 如何使用MVC模式组织JavaWeb应用?
· 程序的DAO层(数据访问层)完成什么任务?
预习检查
· 为什么需要Hibernate?
· Hibernate是什么?
· 使用Hibernate的步骤是?
本章任务
· 使用Hibernate实现:
· 用户的增、删、改操作
· 升级“房屋出租系统”
· 使用Hibernate实现用户注册
· 使用hibernate实现房屋信息的增、删、改
本章目标
· 了解Hibernate基本原理
· 学会编写实体映射文件
· 学会使用Hibernate完成数据增、删、改操作
· 学会在项目中使用Hibernate
为什么使用Hibernate?
· 在编写DAO层代码时,容易出现哪些问题?
· 使用Hibernate后的DAO层代码:
Hibernate是一个优秀的持久化框架
小结
· 是一个主流的持久化框架
· 在JDBC基础上进行封装
· 只需要少量代码就可以完成持久化工作
· 是一个优秀的ORM(对象-关系映射)机制
· 通过映射文件保存映射信息
· 在业务层以面向对象的方式编程,不用考虑数据保存形式
使用Hibernate实现用户添加
· 如何使用Hibernate实现“用户添加”功能?
· 使用Hibernate的“3个准备,7个步骤”
· 准备1:导入Hibernate库(jar包)
· 准备2:添加配置文件 -- hibernate.cfg.xml
<session-factory>
<property name="connection.url">
jdbc:sqlserver://localhost:1433;Database=zf
</property>
<property name="connection.username">sa</property>
<property name="connection.password">accp</property>
<property name="connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="show_sql">true</property>
<mappingresource="com/aptech/jb/entity/User.hbm.xml" />
</session-factory>
· 准备3:添加实体类和映射文件(User.hbm.xml)
package com.aptech.jb.entity;
public class User
implements java.io.Serializable {
private Integer uid;
private String uname;
private String upass;
public User(){ // 默认构造方法
}
// Getter and setter
}
小结
· 使用Hibernate的三项准备工作是?
· 添加Hibernate库
· 添加Hibernate配置文件
· 添加对应表的实体类和映射文件
· Hibernate配置文件中配置了哪些信息?
· Hibernate使用的实体类和之前定义的实体类有什么区别?
· 使用Hibernate,系统中添加一个表的时候,都有哪些准备工作要做?
· 添加实体类
· 添加映射文件
· 在hibernate.cfg.xml中增加
<mappingresource="com/aptech/jb/entity/EntityName.hbm.xml" />
使用Hibernate实现用户添加
public static void main(String[] args) {
Configuration conf = newConfiguration().configure();//1、读取配置文件
SessionFactory sf = conf.buildSessionFactory();// 2、创建SessionFactory
Session session = sf.openSession();// 3、打开Session
Transaction tx = null;
try{
tx = session.beginTransaction();// 4、开始一个事务
//5、持久化操作
Useruser = new User();
user.setUname("Hibernateuser");
user.setUpass("password");
session.save(user);
tx.commit();// 6、提交事务
}catch(Exception e){
if(null!=tx){tx.rollback();}
e.printStackTrace();
}finally{
session.close();// 7、关闭Session
}
}
Hibernate执行过程
使用Hibernate实现数据的加载/删除/修改
· 程序代码
Session session = sf.openSession();
User user = (User)session.get(User.class, id);
session.close();
System.out.println(user.getUname() +"," + user.getUpass());
tx = session.beginTransaction();
User user = this.testLoad(id);
user.setUname("new Name");
session.update(user);
tx.commit();
tx = session.beginTransaction();
User user = this.testLoad(id);
session.delete(user);
tx.commit();
小结
· 简述:使用Hibernate的“3个准备,7个步骤”.
使用工具简化Hibernate开发
· 使用Hibernate开发虽然简化了开发工作,但还要编写额外的配置文件和映射文件,还是很繁琐!
有解决的办法吗?
· 总结一下,刚才演示过程中,MyEclipse工具帮我们做了哪些事情?
1、给项目添加Hibernate支持(自动添加jar包)
2、自动生成hibernate.cfg.xml配置文件
3、生成实体类、映射文件
注意:关键是正确配置了数据库连接信息
· 重新实现租房系统FwxxDAO接口
1、在原项目基础上添加Hibernate支持
2、生成TBL_FWXX表对应的实体和映射文件
3、添加com.aptech.jb.dao.hibimpl.FwxxDAOHibImpl类,实现FwxxDAO接口
· FwxxDAOHibImpl中add方法代码如下。 下面蓝色的代码和del、update方法的代码存在重复,可以采取什么方法精简呢?
public void add(FWXX item) {
Session session =HibernateSessionFactory.getSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.save(item);
tx.commit();
}catch(Exception e){
if(null!=tx) { tx.rollback(); }
e.printStackTrace();
}finally{
session.close();
}
}
在项目中使用Hibernate
public class FwxxDAOHibImpl
extendsBaseHibernateDAO implements FwxxDAO {
public FWXX get (int fwid) {
super.get(FWXX.class,fwid);
}
public void add(FWXX fwxx) {
super.add(fwxx);
}
public void del (int fwid) {
super.del(FWXX.class, fwid);
}
public void update(FWXX fwxx) {
super.update(fwxx);
}
…
}
public abstract class BaseHibernateDAO {
protected void add(Object item){
Transaction tx = null;
Session session = HibernateSessionFactory.getSession();
try {
tx = session.beginTransaction();
session.save(item);
tx.commit();
} catch (Exception e) {
if(null!=tx){ tx.rollback();}
e.printStackTrace();
}finally{
session.close();
}
}
// update,delete,get 方法与之类似
…
}
总结
· 为什么要使用Hibernate?
· Hibernate是什么?
· 使用Hibernate的“3个准备,7个步骤”指的是?
· 使用什么方法可以简化“3个准备” ?
· 使用什么方法可以简化“7个步骤” ?
· 使用Hibernate实现DAO层,比单纯使用JDBC实现优越在哪儿?
总结
1.新建XML文件,右键SRC目录--->xml(basictemplates)--->from scratch那个选项
2.hibernate 配置hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/HibernateConfiguration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<propertyname="connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<propertyname="connection.url">
jdbc:sqlserver://localhost:1433;databasename=zf
</property>
<propertyname="connection.username">sa</property>
<propertyname="connection.password">zhaojing</property>
<propertyname="dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<propertyname="show_sql">true</property>
<propertyname="format_sql">true</property>
<propertyname="hibernate.hbm2ddl.auto">update</property>
<mappingresource="entity/User.hbm.xml"/>
<mappingresource="entity/NewUser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3.实体类配置 NewUser.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>
<classname="entity.NewUser" table="TBL_NewUSER1">
<idname="uid" type="java.lang.Integer">
<generatorclass="native"></generator><--是不是自动增加的-->
</id>
<propertyname="uname" column="UNAME"type="java.lang.String"></property>
<propertyname="upass" column="upass"type="java.lang.String"></property>
<propertyname="uage" column="uage"type="java.lang.Integer"></property>
</class>
</hibernate-mapping>
4.hibernate对数据的操作
-----
(1)写一个父类,封装session
privatestatic Session session;
privatestatic SessionFactory sf;
publicSessionFactory getSf() {
if(sf== null)
{
Configurationconf = new Configuration().configure();// 1¡¢¶ÁÈ¡ÅäÖÃÎļþ
sf= conf.buildSessionFactory();// 2¡¢´´½¨SessionFactory
}
returnsf;
}
publicSession getSession() {
session= getSf().openSession();// 3¡¢´ò¿ªSession
returnsession;
}
定义抽象方法
publicabstract void insert(Object obj);
publicabstract void delete(int id);
publicabstract void update(Object obj);
publicabstract Object select(int id);
(2)只能对主键进行操作
更新session.update(u);
publicvoid update(Object obj) {
if (obj instanceof PetInfo) {
Session session = super.getSession();
PetInfo pi = (PetInfo) obj;
Transaction tx = session.beginTransaction();
try {
PetInfo u = (PetInfo) session.get(PetInfo.class, pi.getPet_id());
u = pi;
session.update(u);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();// ¹Ø±Õ×ÊÔ´
}
}
增加session.save(pi);
删除session.delete(pi);
查询session.get(PetInfo.class, id);