---
title: "Hibernate3学习笔记(一)-hibernate概述和简单实例入门"
author: "Spring_g"
date: "2014-03-29T23:45:08Z"
tags: []
categories: ["企业架构"]
slug: "hibernate3-hibernate"
draft: false
lastmod: "2016-03-21T17:09:30Z"
id: 2038350
url: "https://isource.iteye.com/blog/2038350"
---

一个全新的资源分享平台：[享你所想](http://isource.sinaapp.com)

1.	先扯下什么是hibernate：	
     a)	hibernate(冬眠)->让java对象在数据库中冬眠.
     b)	持久化技术(把数据永久保存到数据库中，广义的理解包括和数据库相关的各种操作)，jdbc io也是持久化技术。
     c)	一个java领域的持久化框架，一个ORM轻量级框架，连接java应用程序和关系型数据库的中间件，对JDBC API封装，负责对象持久化。位于持久化层，封装了所有的数据访问细节，完全体现了面向对象的思想，向业务逻辑层提供面向对象的API，使开发人员把更多的精力放在业务逻辑上。
     d)	hibernate的优点是建立在jdbc的缺点之上，jdbc繁琐的字段操作和sql维护。
2.	接下来先用Hibernate来做一个小例子,看看使用hibernate和直接使用jdbc有便捷之处：
a)	创建数据库 和 数据库表：

```sql
drop database if exists  ishare_hibernate;
create database  ishare_hibernate;
use  ishare_hibernate;

create table  customers(
          id int primary key,
          name varchar(20),
          age int,
birthday datetime,
          married int,
          photo longblob,
          descritpion text
 );
```
//几个不同数据库下数据类型

| 类型 |mysql|sqlserver |oracle|
  |存储图片|longblob|image|blob|
 | 大文本|text|text|clob|
 			
	  			 			
b)	创建Java项目
①.	引入类库 解压hibernate3.0：引入lib/required目录下全部jar+Hibernate核心包+数据库驱动包mysql-connector-java-5.1.7-bin.jar
log4j.jar,slf4j-log4j.jar
在工程下新建lib目录，将jar包拷贝过去 并buildpath。
       ②．在工程源目录新建hibernate.properties 属性文件
			
```java
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/ishare_hibernate
hibernate.connection.username=root
hibernate.connection.password=root
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
```

注释：hibernate.dialect方言是对底层数据库所用自身机制的配置
      ③.创建java bean：Customer.java 
			

```java
public class Customer {
	private Integer id;
	private String name;
	private Integer age;
	private Date birthday;
	private boolean married;
	private byte[] photo;
	private String description;
}//getter setter省略
```

④．新建映射文件 Customer.hbm.xml
	
```xml
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ishare.domain">
	<class name="Customer" table="customers" lazy="false">
		<id name="id" column="id" type="integer">
			<generator class="increment"/>
		</id>
		<property name="name" column="name" type="string" length="20"/>
		<property name="age" column="age" type="integer"/>
		<property name="birthday" column="birthday" type="date"/>
		<property name="married" column="married" type="boolean"/>
		<property name="photo" column="photo" type="binary"/>
		<property name="description" column="description" type="text"/>
         
        
	</class>
</hibernate-mapping>
```

关于映射文件需要说明的几点：
    1.映射文件一般要和对应的实体类放在同一目录下。
    2.hibernate-mapping package属性 可以设置当前javabean所在包路径，这样在使用Customer时就不用每次都是用全路径了
    3.映射文件的dtd文档类型定义，在hibernate3.jar第一个包下最后一个文件中。
    4. <property name="age" column="age" type="integer"/>
   name属性区分大小写，column不区分大小写,
   5.type 为映射类型(具体参考类型映射表)映射类型就是完成sql-java之间转换的。
    如果type属性省略不写，hibernate会通过反射去找对应的java类型
   测试string类型时 type=”java.lang.String”也可以，但是hibernate还得去通过反射去找对应的映射类型，还不如不写。
    6.generator 主键生成策略,其类型会在后面详细介绍 	
⑤．测试类一App.java：配置完后来测试下自己的成果吧
	
```java
/**
 * 测试类
 * @author spring_g
 *
 */
public class APP {
	//会话工厂-相当于 连接池(数据源)
	private static SessionFactory sf = null;
	
	//1.初始化 会话工厂
	static{
		//引入三方框架 类库 配置文件
		try {
			Configuration conf = new Configuration();
			//加载映射文件 通过类找和他在一起的映射文件
			conf.addClass(Customer.class);
			//构建会话工厂，初始化
			sf = conf.buildSessionFactory();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//2.main方法插入测试
	public static void main(String[] args) {
		Customer c = new Customer();
		c.setName("spring");
		insertCustomer(c);
	}

	//3.插入客户
	public static void insertCustomer(Customer c){
		//开启一个新会话
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		s.save(c);
		tx.commit();//提交事务
		s.close();//关闭会话
		
	}
}
```
  ⑥．测试类二Junit4测试对Customer的增删改查：
	
```java
/**
 * 测试基本操作
 * @author spring_g
 *
 */
public class TestCurd {
	//会话工厂-相当于 连接池(数据源)
	private static SessionFactory sf = null;
	/**
	 * 初始会话工厂
	 */
	@BeforeClass
	public static void initSf(){
		//引入三方框架 类库 配置文件
		try {
			Configuration conf = new Configuration();
			//加载映射文件 通过类找和他在一起的映射文件，预先生成sql语句
			conf.addClass(Customer.class);
			//构建会话工厂，初始化
			sf = conf.buildSessionFactory();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Test
	public  void insertCustomer(){
		Customer c = new Customer();
		c.setName("Sean");
		c.setAge(20);
		c.setBirthday(Date.valueOf("2008-12-13"));
		c.setMarried(true);
		c.setDescription("asdfasdfasdfasdfad");
		
		try {
			FileInputStream fis = new FileInputStream("d:/aaa.jpg");
			byte[] bytePhoto = new byte[fis.available()];
			fis.read(bytePhoto);
			fis.close();
			c.setPhoto(bytePhoto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		s.save(c);
		tx.commit();
		s.close();
		
	}
	/**
	 * 查询操作
	 */
	@Test
	public  void loadCustomer(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Customer c = (Customer) s.load(Customer.class, 3);
		byte[] bytes = c.getPhoto();
		try {
			FileOutputStream fos = new FileOutputStream("d:/kkk.jpg");
			fos.write(bytes);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(c.getName());
		tx.commit();
		s.close();
		
	}
	
	/**
	 * hql查询，oop查询操作
	 */
	@Test
	public  void loadCustomerList(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Query query = s.createQuery("from Customer");
		List list = query.list();
		System.out.println(list.size());
		tx.commit();
		s.close();
		
	}
	
	/**
	 * 更新操作
	 * 同一会话更新不需要调用update
	 */
	@Test
	public  void updateCustomer(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Customer c = (Customer) s.load(Customer.class, 3);
		c.setName("NewName");
		//不需要调用update方法  和对象状态有关
		tx.commit();
		s.close();
		
	}
	
	/**
	 * 更新操作-关闭会话后更新需要调用update()
	 */
	@Test
	public  void updateCustomer1(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		//查询不到会抛异常
		Customer c = (Customer) s.load(Customer.class, 3);
		c.setName("NewName");
		tx.commit();
		s.close();
		
		s = sf.openSession();//新开启一会话
		tx = s.beginTransaction();
		c.setName("updateMethod");
		s.update(c);
		tx.commit();
		s.close();
		
	}
	
	/**
	 * 更新操作-设置主键值
	 * 更新把整个对象状态存储到数据库中
	 */
	@Test
	public  void updateCustomer2(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Customer c = new Customer();
		//会将该对象的状态全部更新到数据库
		c.setId(4);//不设置id时 报异常  临时对象异常
		s.update(c);
		tx.commit();
		s.close();
		
	}
	
	/**
	 * 删除操作 先查询
	 */
	@Test
	public  void deleteCustomer(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Customer c = (Customer) s.load(Customer.class, 4);
		s.delete(c);
		tx.commit();
		s.close();
		
	}
	/**
	 * 删除操作new出来给id
	 */
	@Test
	public  void deleteCustomer2(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Customer c = new Customer();
		c.setId(4);
		s.delete(c);
		tx.commit();
		s.close();
		
	}
	
	/**
	 * 批量删除
	 */
	@Test
	public  void deleteBatchCustomer(){
		Session s = sf.openSession();
		//开始事务 acid
		Transaction tx = s.beginTransaction();
		Query query = s.createQuery("delete from Customer where id>3");
		query.executeUpdate();
		tx.commit();
		s.close();
		
	}
}
```

通过以上简单例子的入门，一定感觉hibernate确实是个不错的东西，给我们从繁琐的sql中解脱了出来，完全从面向对象的角度来实现对数据的持久化的操作。![](http://1.gshare.duapp.com)
**<span style="color:darkred">自己在平时的学习中也整理了一些比较好的资源，现在分享出来希望也能对你有所帮助：[分享资源入口](http://isource.sinaapp.com/)</span>**