什么是Hibernate
1、ORM:(Object/Relationship Mapping)
对象/关系映射
2、写SQL语句的缺点:
- 不同的数据库使用的SQL语法不同。比如:PL/SQL(oracle数据库)与T/SQL(微软版本)
- 同样的功能在不同的数据库中有不同的实现方式。比如分页SQL
- 程序过分依赖SQL对程序的一直及扩展,维护等带来很大的麻烦。
3、Hibernate是一种能够减少对SQL语句依赖,可行的ORM框架技术。
Hibernate简介
- Hibernate是java领域的一款开源的ORM框架技术
- Hibernate对JDBC进行了非常轻量级的对象封装
Hibernate在我们的应用程序中充当着什么样的角色呢?
举例,如下图所示:我们要开发不同的系统
持久化层 — 处于业务逻辑层和数据库之间的一个角色
作用 – 把程序中生成的对象持久化到数据库中,换句话说,就是把这些对象通过对象关系映射保存到数据库的表中
其他主流的ORM框架技术
①MyBtis : 前身就是著名的iBatis
②Toplink:后被Oracle收购,并重新包装为Oracle AS TopLink
③EJB:本身是JAVAEE的规范
编写第一个Hibernate例子
导入Hibetnate必须的jar包
hibernate-release-4.2.4.final\lib\required
导入Mysql的jdbc驱动
Mysql-connector-java-5.5.7-bin.jar
导入junit4的jar包
Junit-4.10.jar
MyEclipse 10.xJavaproject配置Hibernate方法
项目名称–>右键–>MyEclipse–>add hibernate capabilities
实体化类
package STU;
import java.util.Date;
/*--Java Bean的几个基本要求--
* 1,公有的类
* 2,提供公有得到不带参数的默认的构造方法
* 3,属性私有
* 4,属性setter/getter方法
* */
public class Student {
private int id;
private String name;
private String address;
private Date birthday;
private String gender;
public Student() {
}
public Student(int id, String name, String gender, String address,
Date birthday ) {
// super();
this.id = id;
this.name = name;
this.address = address;
this.birthday = birthday;
this.gender = gender;
}
....getter & setter 方法...此处省略
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", address=" + address
+ ", birthday=" + birthday + ", gender=" + gender + "]";
}
}
JUnit进行单元测试
@Test:测试方法
@Before:初始化方法
@After:释放资源
执行顺序:Before–>Test–>After
工程名–>右键–>SourceFolder–>FolderName为test–>新建StudentTest类
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Settings;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import STU.Student;
/*
* JUnit测试
* */
public class StudentTest {
private Session session;
private SessionFactory sessionFactory ;
private Transaction transaction ;
@Before
public void init(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建会话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
//会话对象
session = sessionFactory.openSession();
if(session!=null){
System.out.println("session对象创建成功");
}else{
System.out.println("session对象创建失败");
}
//开启事务,此处注释是为了检验doWork()方法的
//transaction = session.beginTransaction();
}
@After
public void destory(){
transaction.commit();//先提交事务
session .close();//关闭对话
sessionFactory.close();//关闭工厂
}
@Test
public void testSaveStudent(){
Student student = new Student(1,"张三丰","男","武当山",new Date());
//使用doWork方法,传入work的匿名内部类进行提交内容至数据库
session.doWork(new Work() {
public void execute(Connection arg0) throws SQLException {
// TODO Auto-generated method stub
arg0.setAutoCommit(true);
}
});
session.save(student);//保存对象进数据库
session.flush();//刷新输出sql语句,使用doWork()方法时候使用
}
}
hibernate.cfg.xml常用配置
- hibernate.show_sql 编码阶段便于测试
- hibernate.format_sql 排版问题,建议设置为true
- hbm2ddl.auto 可以帮助由 java代码生成数据库脚本,进而生成具体的表结构。create|update|create-drop|validate
- hiberante.default_schema 默认的数据库
- hibernate.dialect 配置Hibernate数据库方言
- hiberante的前缀可以省略,即:hibernate.dialect等同于dialect
需要的方法和对象
configuration:读取配置文档
sessionFactory:对象关系映射文件
session:操作数据库的对象,类似于JDBC中的connection
session的方法:save,delete,update,createQuery()
Transaction:commit
session和connection:多对一关系,一个connection服务多个session,每个session都有与之对应的connection
1.不建议直接使用jdbc的connection操作数据库,而是通过session操作数据库。
2.session可以了解为操作数据库的对象,操作数据库之前必须先获取session的实例
3.session与connection,是多对一关系,每个session都有一个与之对应的connection,一个connection不同时刻可以供多个session使用。
4.把对象保存到关系数据库中需要调用session的各种方法:save(),update(),delete(),createQuery
transaction 事务
hibrenate操作都是封装在事物中,并且默认是非自动提交方式,所以session保存对象时,如果不开启事物,并且手工提交事物,对象并不会真正保存在数据库中
打开session后,必须提交事务(Transaction),否则数据不会真正保存在数据库中
beginTransaction,commit(可用session.doWork(new Work(){}))方法来实现
session.flush():输出sql语句
如何获得session对象
(1)openSessionion();
(2)getCurrentSession();
如果使用getCurrentSession需要在hibernate.cfg.xml文件中进行配置:
如果是本地事务(jdbc事务)
thread
如果是全局事务(jta事务)
jta
Session的两种获得方法 的 区别
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;
import STU.Student;
/*
* Session测试类
* openSession与getCurrentSession的区别:
*(1)getCurrentSession在事务提交或者回滚之后会自动关闭,而openSesssion需要你手动关* 闭。如果使用openSession而没有手动关闭,多次之后会导致连接池溢出!
*(2)openSession每次创建新的session对象,getCurrentSession使用现有的session对象
* */
public class SessionTest {
@Test
public void testOpenSession(){
//创建配置对象,并调用配制方法
Configuration config = new Configuration().configure();
//创建注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建sessionFactory对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//会话对象
Session session1 = sessionFactory.openSession();
Session session2 = sessionFactory.openSession();
System.out.println(session1==session2);//false
/*
if (session1 != null) {
System.out.println("session对象创建成功");
} else {
System.out.println("session对象创建失败");
}
*/
//创建事务对象
Transaction transaction = session1.beginTransaction();
}
@Test
public void testGetCurrentSession(){
// 创建配置对象,并调用配制方法
Configuration config = new Configuration().configure();
// 创建注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 创建sessionFactory对象
SessionFactory sessionFactory = config
.buildSessionFactory(serviceRegistry);
// 会话对象,使用getCurrentSession必须先在hibernate.cfg.xml中配置,下面什么都不输出
Session session1 = sessionFactory.getCurrentSession();
Session session2 = sessionFactory.getCurrentSession();
System.out.println(session1 == session2);// true
/*
* if (session1 != null) { System.out.println("session对象创建成功"); } else {
* System.out.println("session对象创建失败"); }
*/
}
/*
* 打印的两个HashCode是不一样的
*
* */
@Test
public void testSaveStudentAsOpenSession(){
// 创建配置对象,并调用配制方法
Configuration config = new Configuration().configure();
// 创建注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 创建sessionFactory对象
SessionFactory sessionFactory = config
.buildSessionFactory(serviceRegistry);
// 会话对象
Session session1 = sessionFactory.openSession();
Transaction transaction = session1.beginTransaction();
Student s = new Student(1, "小李", "男", "上海", new Date());
session1.doWork(new Work() {
public void execute(Connection arg0) throws SQLException {
// TODO Auto-generated method stub
System.out.println("session1`s connection hashcode is :"
+ arg0.hashCode());
}
});
session1.save(s);
transaction.commit();
// session1.close();
Session session2 = sessionFactory.openSession();
transaction = session2.beginTransaction();
s = new Student(2, "小王", "男", "北京", new Date());
session1.doWork(new Work() {
public void execute(Connection arg0) throws SQLException {
// TODO Auto-generated method stub
System.out.println("session2`s connection hashcode is :"
+ arg0.hashCode());
}
});
session1.save(s);
transaction.commit();
}
/*
* 打印的两个HashCode是一样的
* */
@Test
public void testSaveStudentAsGetCurrentSession(){
// 创建配置对象,并调用配制方法
Configuration config = new Configuration().configure();
// 创建注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 创建sessionFactory对象
SessionFactory sessionFactory = config
.buildSessionFactory(serviceRegistry);
// 会话对象,使用getCurrentSession必须先在hibernate.cfg.xml中配置,下面什么都不输出
// 会话对象
Session session1 = sessionFactory.getCurrentSession();
Transaction transaction = session1.beginTransaction();
Student s = new Student(1, "小李", "男", "上海", new Date());
session1.doWork(new Work() {
public void execute(Connection arg0) throws SQLException {
// TODO Auto-generated method stub
System.out.println("session1`s connection hashcode is :"
+ arg0.hashCode());
}
});
session1.save(s);
transaction.commit();//getCurrentSession是单例模式,每次提交后都会自动释放资源
// session1.close();
Session session2 = sessionFactory.getCurrentSession();
transaction = session2.beginTransaction();
s = new Student(2, "小王", "男", "北京", new Date());
session1.doWork(new Work() {
public void execute(Connection arg0) throws SQLException {
// TODO Auto-generated method stub
System.out.println("session2`s connection hashcode is :"
+ arg0.hashCode());
}
});
session1.save(s);
transaction.commit();
}
}
openSession与getCurrentSession的区别
(1)getCurrentSession在事务提交或者回滚之后会自动关闭,而openSesssion需要你手动关闭。如果使用openSession而没有手动关闭,多次之后会导致连接池溢出!
(2)openSession每次创建新的session对象,getCurrentSession使用现有的session对象
openSession与getCurrentSession
openSession 每次使用都是打开一个新的session,使用完需要调用close方法关闭session;
getCurrentSession 是获取当前session对象,连续使用多次时,得到的session都是同一个对象,这就是与openSession的区别之一 ;
一般在实际开发中,往往使用getCurrentSession多,因为一般是处理同一个事务,所以在一般情况下比较少使用openSession;
hbm.xml常用配置
<hibernate-mapping
schema="schemaName" //模式的名字
catalog="catalogName" //目录的名称
default-cascade="cassade_style" //级联风格 @
default-access="field/property/CalssName" //访问策略 @
default-lazy="true/false" //加载策略 @
package="packagename" //默认包名
/>
<class
name="ClassName" //对应映射的类
table="tableName" //对应映射数据库的表
batch-size="N" //抓取策略,一次抓取多少记录
where="condition" //条件 eg:抓取条件
entity-name="EntiyName" //如果需要映射多张表
/>
<id //表的主键
name="propertyName" //对应的属性
type="typeName" //对应类型
column="column_nam" //映射数据库中表当中字段名的名称
length="length" //指定长度
<generator class="generatorClass"/> //主键生成策略
主键生成策略
其中:native 对应MySQL的auto-incremented,字段的类型必须是整型;assign手工赋值。