Hibernate入门实例

Hibernate入门实例
1. 概述
Hibernate是一个优秀的开源ORM框架,会自动生成SQL语句,支持数据库事务管理。开发者只需通过配置hibernate.cfg.xml和具体的持久化类映射文件,通过加载配置文件,获得session,即可以进行数据库操作。Hibernate还支持面向对象的Hibernate 查询语言HQL,这个框架本质上是对JDBC的封装,但通过配置文件的形式使得我们脱离了繁琐的偏于底层的JDBC操作和资源获取释放操作,大大提高了开发效率。
2. Hibernate配置文件hibernate.cfg.xml
这个文件位于类路径下,即src根目录下,默认情况下会从这个路径下加载配置文件。这个配置文件主要提供数据库的连接信息和持久化类配置文件。
<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库连接的URL -->
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <!-- 数据库连接用户名 -->
        <property name="connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name="connection.password">201314</property>
        <!-- Hibernate方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 打印SQL语句,将在控制台输出SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 映射文件,位于类路径下  -->
        <mapping resource="com/mr/product.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

3.编写持久化类com.mr.Product
这个类必须符合JavaBean规范,也就是不能扩展其他类,不能实现其他接口,必须提供无参构造函数,提供getter和setter方法。
package com.mr;

/**
 * Created by gzx on 16-11-22.
 */
public class Product {
    private int id;
    private String name;
    private Double price;
    private String factory;
    private String remark;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getFactory() {
        return factory;
    }

    public void setFactory(String factory) {
        this.factory = factory;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", factory='" + factory + '\'' +
                ", remark='" + remark + '\'' +
                '}';
    }
}

4. Product类的映射文件
在上述hibernate.cfg.xml下有这么一句<mapping resource="com/mr/product.hbm.xml"/>
这句话表示加载映射文件com/mr/product.hbm.xml。这个文件位于类路径下,是实现ORM的关键文件,是Java对象和数据库表对应关系的桥梁。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- 类com.mr.Product 和 数据库表test.product关联-->
    <class name="com.mr.Product" table="product">
        <!-- id值,这里提供主键,对应数据库表product的列id -->
        <id name="id" column="id" type="int">
            <generator class="native"/>
        </id>
        <!-- 姓名,name值数java类的属性,而column值是数据库列名 -->
        <property name="name" type="string" length="45">
            <column name="name"/>
        </property>
        <!-- 价格 -->
        <property name="price" type="double">
            <column name="price"/>
        </property>
        <!-- 工厂 -->
        <property name="factory" type="string" length="200">
            <column name="factory"/>
        </property>
        <!-- 备注 -->
        <property name="remark" type="string" length="200">
            <column name="remark"/>
        </property>
    </class>
</hibernate-mapping>


5. 数据库表的建立
这里使用的是MySQL来建立数据库表:
CREATE TABLE `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(45) DEFAULT NULL,
  `price` double DEFAULT NULL,
  `factory` char(200) DEFAULT NULL,
  `remark` char(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

6. session的获取
要获取session,必须加载hibernate.cfg.xml文件,初始化sessionFactory,进而通过sessionFactory获得session。
由于多个线程共享一个session是不安全的,这里通过ThreadLocal的形式获得安全的session。提供一个获取session的工具类。
package com.mr;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory = null;
    //初始化静态块
    static {
        try {
            //默认加载src下的hibernate.cfg.xml文件
            Configuration cfg = new Configuration().configure();
            sessionFactory = cfg.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("fail to load sessionFactory");
            e.printStackTrace();
        }
    }

    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession(): null;
            threadLocal.set(session);
        }

        return session;
    }

    private static void rebuildSessionFactory() {
        try {

            Configuration cfg = new Configuration().configure();
            sessionFactory = cfg.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("fail to build sessionFactory");
            e.printStackTrace();
        }
    }

    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close();
        }
    }
}

7. 测试实例
通过获取session,进而利用session的相关方法,就可以进行数据库操作,非常简单!同时说明Hibernate可用于Java SE和Java EE的开发。
注意:必须在lib下加如mysql的driver jar包和hibernate lib下必须的jar包。
package com.mr;

import com.mr.HibernateUtil;
import org.hibernate.Session;

/**
 * Created by gzx on 16-11-22.
 */
public class AddProduct {
    private static void insert(){
        Session session = null;
        Product product = new Product();
        product.setName("Java Web编程宝典");
        product.setPrice(79.00);
        product.setRemark("无");
        product.setFactory("明日科技");
        session = HibernateUtil.getSession();
        //开启事务,其他事务对该表上了锁,其他对该表的操作将不能执行
        try {
            session.beginTransaction();
            session.save(product); //将产生insert语句
            product.setFactory("NUPT"); //将产生update语句
            session.getTransaction().commit();
        }catch(Exception e){
            session.getTransaction().rollback();
            System.out.println(e.getMessage());
        }
        finally{
            HibernateUtil.closeSession();
        }

    }

    public static void main(String[] args){
        insert();
    }
}

这时数据库中将添加一条记录:
|  1 | Java Web编程宝典     |    79 | NUPT               | 无     |

控制台将输出:
Hibernate: insert into product (name, price, factory, remark) values (?, ?, ?, ?)
Hibernate: update product set name=?, price=?, factory=?, remark=? where id=?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值