Hibernate简介

1 篇文章 0 订阅
1 篇文章 0 订阅
  Hibernate简介

Hibernate寓意:Let Java objects hibernate in the relational database.
Hibernate 是Java应用和关系数据库之间的桥梁,负责Java对象和关系数据库之间的映射的ORM中间件。Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java开发人员可以随心所欲的使用对象编程思维来操纵数据库。简单的说就是:
1.封装了通过JDBC访问数据库操作。
2.向上层应用提供访问面向对象数据访问的API。

创建Hibernate配置文件
通过一个例子practice 演示如何运用Hibernate来访问关系数据库。
Practice 工程的功能:
通过Hibernate保存客户(customer)信息。
其Hibernate应用结构图如下:

―――――――――――――――――――――――――――
Practice 应用
Customer Class ; action Class;Business Class
――――――――――――――――――――――――――――


――――――――――――――――――――――――――――
Hibernate xml
对象-关系映射文件           Hibernate ApI
                             Hibernate 配置文件
――――――――――――――――――――――――――――


――――――――――――――――――――――――――――
关系数据库(Mysql)
CUSTOMERS 表
――――――――――――――――――――――――――――


创建持久化类
Hibernate 从Hibernate配置文件中读取和数据库连接相关的信息。
配置文件有两种形式:
一种是XML格式的文件:hibernate.cfg.xml
一种是Java属性文件:hibernate.properties
这个实例中我们将使用hibernate.cfg.xml。

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="show_sql">true</property>
        <property name="use_outer_join">false</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
        <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/netstore</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.useUnicode">true</property>
        <property name="connection.characterEncoding">gb2312</property> 
        <mapping resource ="hbm/Customers.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


插入位置在src目录下:

创建O/R对象-关系映射文件
创建持久化的类Customer.java

package entity;

import java.io.Serializable;

public class Customers implements Serializable {

        private Integer id;

        private String name;

        private int age;

        public Customers() {
        }

        public int getAge() {
                return age;
        }

        public void setAge(int age) {
                this.age = age;
        }

        public Integer getId() {
                return id;
        }

        public void setId(Integer id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }
}


Get/set 方法的命名必须符合JavaBean的规范,否则Hibernate会报出异常,具体请参照相关资料。

关于Serializable接口:
Hibernate 并不要求持久化类必须实现java.io.Serializable接口,但是对于采用分布式结构的Java应用,当Java对象在不同的进程节点之间传输时,这个对象必须实现这个接口;如果希望对HttpSession中存放的Java对象进行持久化,那么这个Java对象必须实现 Serializable接口。
关于不带参数的构造方法:

public Customers() {
        }


Hibernate要求持久化类必须提供一个不带参数的默认的构造方法,原因请参考相关资料。

创建Mysql数据库
数据库名称:netstroe
Customer表DDL定义如下:
CREATE TABLE `customers` (
  `Id` bigint(20) NOT NULL default '0',
  `name` varchar(15) default NULL,
  `age` int(11) default NULL,
  PRIMARY KEY  (`Id`)
) TYPE=MyISAM;


创建对象-关系映射文件
创建对象-关系映射文件:Customers.hbm.xml
代码如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
    
<hibernate-mapping>
<!-- 
    Created by the Middlegen Hibernate plugin

    http://boss.bekk.no/boss/middlegen/
    http://hibernate.sourceforge.net/
-->

<class 
    name="entity.Customers" 
    table="customers"
>

    <id
        name="id"
        type="java.lang.Integer"
        column="id"
    >
        <generator class="assigned" />
    </id>

    <property
        name="name"
        type="java.lang.String"
        column="name"
        length="15"
    />
    <property
        name="age"
        type="int"
        column="age"
        length="11"
    />
</class>
</hibernate-mapping>


引入Hibernate所需的jar包
Hibernate2.jar、hibernate-tools.jar

通过Hibernate API 访问MYSQL数据库
创建业务逻辑类:useHibernate.java
代码如下:
package business;

import entity.Customers;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

public class useHibernate {
        public static SessionFactory sessionFactory;

        /** 初始化Hibernate,创建SessionFactory实例 */
        public void saveCustomers(Customers customers) throws Exception {
                Configuration config = null;
                config = new Configuration().configure();
                // 创建一个SessionFactory 实例
                sessionFactory = config.buildSessionFactory();
                Session session = sessionFactory.openSession();
                Transaction tx = null;
                try {
                        /* 开始一个事务 */
                        tx = session.beginTransaction();
                        session.save(customers);
                        /* 提交事务 */
                        tx.commit();
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        if (tx != null)
                                tx.rollback();
                        throw e;
                } finally {
                        session.close();
                }
        }
}


测试Hibernate配置是否成功
创建Junit测试:testhibernate.java
有关Junit请参考相关资料:
package test;

import business.useHibernate;
import entity.Customers;
import junit.framework.TestCase;

public class testhibernate extends TestCase {
        public void testSaveCustomers() {
                Customers customers = new Customers();
                customers.setId(new Integer(330121));
                customers.setAge(24);
                customers.setName("huhpreal");
                useHibernate usehibernate = new useHibernate();
                try {
                        usehibernate.saveCustomers(customers);
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}


查看后台打印信息:
(cfg.Environment                     403 ) Hibernate 2.0.3
(cfg.Environment                     432 ) hibernate.properties not found
(cfg.Environment                     452 ) using CGLIB reflection optimizer
(cfg.Environment                     462 ) JVM proxy support: true
(cfg.Configuration                   703 ) Configuration resource: /hibernate.cfg.xml
(cfg.Configuration                   270 ) Mapping resource: hbm/Customers.hbm.xml
(cfg.Binder                          178 ) Mapping class: entity.Customers -> customers
(cfg.Configuration                   885 ) Configured SessionFactory: null
(cfg.Configuration                   492 ) processing one-to-many association mappings
(cfg.Configuration                   503 ) processing foreign key constraints
(impl.SessionFactoryImpl             132 ) building session factory
(dialect.Dialect                     83  ) Using dialect: net.sf.hibernate.dialect.MySQLDialect
(connection.DriverManagerConnectionProvider 41  ) Hibernate connection pool size: 20
(connection.DriverManagerConnectionProvider 70  ) using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/netstore
(connection.DriverManagerConnectionProvider 71  ) connection properties: {useUnicode=true, user=root, password=123456, characterEncoding=gb2312}
(impl.SessionFactoryImpl             162 ) Use outer join fetching: false
(impl.SessionFactoryImpl             185 ) Use scrollable result sets: true
(impl.SessionFactoryImpl             186 ) JDBC 2 max batch size: 15
(impl.SessionFactoryImpl             194 ) echoing all SQL to stdout
(impl.SessionFactoryObjectFactory    82  ) no JDNI name configured
(impl.SessionFactoryImpl             269 ) Query language substitutions: {}
Hibernate: insert into customers (name, age, id) values (?, ?, ?)


Hibernate 配置使用成功

查看数据库:

插入成功!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值