一个全新的资源分享平台:[url=http://isource.sinaapp.com]享你所想[/url]
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) 建立数据库 和 数据库表[Mysql数据库]:
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
);
//几个不一样数据库下数据类型
[table]
| 类型 |mysql|sqlserver |oracle|
|存储图片|longblob|image|blob|
| 大文本|text|text|clob|
[/table]
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 属性文件
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
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
<!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:配置完后来测试下本身的成果吧
/**
* 测试类
* @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的增删改查:
/** * 测试基本操做 * @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中解脱了出来,彻底从面向对象的角度来实现对数据的持久化的操做。[img]http://1.gshare.duapp.com[/img] [b][color=darkred]本身在平时的学习中也整理了一些比较好的资源[Java,Python,前端,PHP,摄影...],如今分享出来但愿也能对你有所帮助:[url=http://isource.sinaapp.com/]分享资源入口[/url][/color][/b]