Hibernate
学习一门新技术,首先要懂三个条件,是什么,为什么,怎么办。
首先Hibernate是什么?
1.是一个开源代码的对象关系映射框架,对JDBC进行了非常轻量级的对象封装,即是一个
ORM映射工具。2.可以完成数据持久化,即是一个
优秀的持久化解决方案。这里提到ORM(Object-Relation Mapping)对象-关系映射,其作用是实现Java对象到关系数据库表的自动持久化。持久化是指瞬时数据和持久数据转换的机制,即内存中的数据与硬盘中的数据转换的过程。I/O流,JDBC,XML都实现了持久化。
Hibernate是一个连接Java应用程序和关系数据库的中间件,对JDBC API进行了封装,负责了Java对象的持久化,并且建立面向对象的域模型和关系数据模型之间的映射。Hibernate在分层的软件架构中位于持久层,封装了所有数据访问细节,是业务逻辑层可以专注于实现业务逻辑。
Hibernate核心API:
Class Configuration 负责配置并启动Hibernate,创建SessionFactory对象。(读取hibernate.cfg.xml信息)
Interface SessionFactory 负责初始化Hibernate,充当数据存储源的代理,创建Session对象。
Interface Session 负责保存、更新、删除、加载和查询对象。
Interface Transaction 管理事务
Interface Query Criteria 执行数据库查询
使用Hibernate框架有两种方式:1.映射文件 2.注解
准备:Hibernate jar包,位于\jar\hibernate-release-4.3.6.Final\lib\required以及数据库驱动包
使用映射文件方式:
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 驱动 -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.25.116.164:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<!-- 指明数据库 -->
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 添加映射文件 一个Bean对应一行,映射文件为resource,并且分隔符为‘/’ -->
<mapping resource = "com/neusoft/model/UserInfo.hbm.xml"/>
</session-factory>
<h2><p><pre name="code" class="java" style="font-size: 13.3333339691162px;"><span style="font-weight: normal;"><hibernate-configuration></span>
映射文件
通过UserInfo生成UserInfo.hbm.xml映射文件:<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-10-19 12:01:22 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.neusoft.model.UserInfo" table="USERINFO">
<!-- 主键列 -->
<!-- name对应Bean中的属性 -->
<id name="userId" type="java.lang.Integer">
<!-- 数据库表中的列名,generator表示<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">在插入数据的时候主键由程序处理</span> -->
<column name="USERID" />
<generator class="assigned" />
</id>
<property name="userName" type="java.lang.String">
<!-- 数据库表中的列名 -->
<column name="USERNAME" />
</property>
<property name="userSex" type="java.lang.String">
<!-- 数据库表中的列名 -->
<column name="USERSEX" />
</property>
</class>
</hibernate-mapping>
创建一个HibernateUtils.class方便使用:
package com.neusoft.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* Hibernate工具类
*/
public class HibernateUtil {
private static SessionFactory sessionFactory;
/**
* 加载一次
*/
static{
//读取配置文件hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
//注册信息
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
//建立工厂
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
/**
* @return Session对象
*/
public static Session getSession(){
return sessionFactory.openSession();
}
/**
* 关闭当前Session对象
*/
public static void closeSession(Session session){
if(session!=null && session.isOpen()){
session.close();
}
}
}
编写一个BaseDao进行数据库操作:
package com.neusoft.dao;
import java.io.Serializable;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.neusoft.util.HibernateUtil;
public class BaseDao {
/**
* 保存
*/
protected final void save(Object obj){
Transaction transaction = null;
Session session = null;
try {
//得到一个Session对象
session = HibernateUtil.getSession();
//开启事务
transaction = session.beginTransaction();
//保存对象
session.save(obj);
//提交事务
transaction.commit();
} catch (Exception e) {
//异常,回滚事务
if(transaction != null){
transaction.rollback();
}
throw new RuntimeException("Error: BaseDao.save()!",e);
}finally{
//关闭Session
HibernateUtil.closeSession(session);
}
}
/**
* 查询
* @param c Bean
* @param s 对象主键
* @return 一个Bean对象
*/
protected final <T>T get(Class c,Serializable s){
Session session = null;
Object object = null;
try {
session = HibernateUtil.getSession();
object = session.get(c, s);
} catch (Exception e) {
throw new RuntimeException("Error: BaseDao.get()!",e);
}finally{
//关闭Session
HibernateUtil.closeSession(session);
}
return (T)object;
}
/**
* 删除
*/
protected final void delete(Object object){
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
session.delete(object);
} catch (Exception e) {
//异常,回滚事务
if(transaction != null){
transaction.rollback();
}
throw new RuntimeException("Error: BaseDao.delete()!",e);
}finally{
//关闭Session
HibernateUtil.closeSession(session);
}
}
/**
* 修改
*/
protected final void update(Object object){
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
session.update(object);
} catch (Exception e) {
//异常,回滚事务
if(transaction != null){
transaction.rollback();
}
throw new RuntimeException("Error: BaseDao.update()!",e);
}finally{
//关闭Session
HibernateUtil.closeSession(session);
}
}
}
通过JUnit测试,测试类:
package com.neusoft.dao;
import org.junit.Test;
import com.neusoft.entity.UserInfo;
public class UserInfoDaoTest {
private UserInfoDao userInfoDao = new UserInfoDao();
@Test
public void testSave(){
// Session session = HibernateUtil.getSession();
// Assert.assertNotNull(session);
UserInfo user = new UserInfo();
user.setUserId(1);
user.setUserName("用户4");
user.setUserSex("女");
user.setUserAge(16);
userInfoDao.save(user);
System.out.println("end!");
}
}
注解
注解和映射文件的不同在于JavaBean,注解不需要写JavaBean的映射文件。只是hibernate.cfg.xml文件有点不同.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">xukai</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.25.116.164:1521:orcl</property>
<property name="hibernate.connection.username">xukai</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 此处为Class -->
<mapping class="com.neusoft.entity.UserInfo"/>
</session-factory>
</hibernate-configuration>
另外JavaBean类中:
package com.neusoft.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
//标识
@Entity
//数据库中的表名
@Table(name="user_info")
public class UserInfo {
//主键
@Id
//数据库表中的列名
@Column(name="user_id")
@SequenceGenerator(name="sequence_user_info",sequenceName="seq_user_info_id")
@GeneratedValue(generator="sequence_user_info",strategy=GenerationType.SEQUENCE)
private Integer userId;
//数据库表中的列名
@Column(name="user_name")
private String userName;
//数据库表中的列名
@Column(name="user_sex")
private String userSex;
//数据库表中的列名
@Column(name="user_age")
private Integer userAge;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
}