Hibernate 之 How

  • 分享自:

    http://blog.csdn.net/jnqqls/article/details/8242520


    在上一篇文章Hibernate 之 Why? 中对Hibernate有了一个初步的了解.接下来我们将从How的角度,也就是如何使用Hibernate来进行学习.

    •         Hibernate是一个开源框架,而我们在项目中使用框架的时候都要对所使用的框架进行相关的环境搭建,下面的步骤便是.
      •  创建一个Java项目Hibernate_first
      •  创建User Library,Hibernate核心文件中加入依赖包.
        • HIBERNATE_HOME/lib/*.jar
        • HIBERNATE_HOME/hibernate3.jar
        • 加入数据库驱动(此例子中用mysql驱动)

    UserLiberty部分截图

    •  创建核心配置文件hibernate_cfg.xml
      • 链接数据库相关的配置
      • 配置数据库适配器.可以直接使用相关数据库的相关特点.

    • [html]  view plain copy print ?
      1.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
      2.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
      3.       
      4.     <hibernate-configuration>  
      5.         <session-factory>  
      6.               
      7.             <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>  
      8.               
      9.             <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_firstproperty>  
      10.               
      11.             <property name="hibernate.connection.username">rootproperty>  
      12.               
      13.             <property name="hibernate.connection.password">rootproperty>  
      14.               
      15.             <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>  
      16.               
      17.             <property name="hibernate.show_sql">trueproperty>  
      18.               
      19.             <property name="hibernate.format_sql">trueproperty>  
      20.               
      21.               
      22.             <mapping resource="com/tgb/hibernate/User.hbm.xml"/>  
      23.         session-factory>  
      24.     hibernate-configuration>  

     

    •        环境搭建完毕之后,接下来我们将会用面相对象的思想来完成对数据库表的创建.和我们以前的先建表有所不同,Hibernate是将类映射到关系库数据中的表.接下来建立User.

    [java]  view plain copy print ?
    1. package com.tgb.hibernate;  
    2.       
    3.     import java.util.Date;  
    4.       
    5.     /** 
    6.      *  
    7.      * @title    创建User类    
    8.      * @author   jnqqls 
    9.      * @group    TGB 
    10.      * @version  1.0 
    11.      * @datetime 2012-11-30上午10:15:25 
    12.      * @comments 
    13.      */  
    14.     public class User {  
    15.         //编号  
    16.         private String id;  
    17.         //姓名  
    18.         private String name;  
    19.         //密码  
    20.         private String password;  
    21.         //创建时间  
    22.         private Date createTime;  
    23.         //失效时间  
    24.         private Date expireTime;  
    25.       
    26.         public String getId() {  
    27.             return id;  
    28.         }  
    29.       
    30.         public void setId(String id) {  
    31.             this.id = id;  
    32.         }  
    33.       
    34.         public String getName() {  
    35.             return name;  
    36.         }  
    37.       
    38.         public void setName(String name) {  
    39.             this.name = name;  
    40.         }  
    41.       
    42.         public String getPassword() {  
    43.             return password;  
    44.         }  
    45.       
    46.         public void setPassword(String password) {  
    47.             this.password = password;  
    48.         }  
    49.       
    50.         public Date getCreateTime() {  
    51.             return createTime;  
    52.         }  
    53.       
    54.         public void setCreateTime(Date createTime) {  
    55.             this.createTime = createTime;  
    56.         }  
    57.       
    58.         public Date getExpireTime() {  
    59.             return expireTime;  
    60.         }  
    61.       
    62.         public void setExpireTime(Date expireTime) {  
    63.             this.expireTime = expireTime;  
    64.         }  
    65.       
    66.     }  


     

    • 接下来是Hibernate中核心的地方:建立映射文件User.hbm.xml.如何将一个类映射成数据库中的一个表?它们之间的映射模型如下
      • 映射模型
      • 创建映射文件User.hbm.xml并完成相关映射.

       

    [html]  view plain copy print ?
    1. xml version="1.0"?>  
    2.     
    3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    4.         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
    5.     <hibernate-mapping>  
    6.           
    7.         <class name="com.tgb.hibernate.User" >  
    8.                
    9.             <id name="id">  
    10.                 <generator class="uuid">generator>  
    11.             id>  
    12.               
    13.             <property name="name"/>  
    14.             <property name="password"/>  
    15.             <property name="createTime"/>  
    16.             <property name="expireTime"/>  
    17.         class>  
    18.     hibernate-mapping>  

    • 类建好,映射也完成,那么如何将类转化成数据库中的实际表呢?接下来我们将会把User类导入数据库表
      • 为了让Hibernate识别实体类.需要将User.htm.xml加入核心配置文件Hibernate.cfg.xml.
      • 编写工具栏ExportDB.java,将我们描述的htm文件生成ddl.也就是hbm2ddl
      • [html]  view plain copy print ?
        1. package com.tgb.hibernate;  
        2.       
        3.     import org.hibernate.cfg.Configuration;  
        4.     import org.hibernate.tool.hbm2ddl.SchemaExport;  
        5.     /**  
        6.      *   
        7.      * @title   将hbm生成ddl 将我们描述的htm文件生成ddl.也就是hbm2ddl  
        8.      * @author   jnqqls  
        9.      * @group    TGB  
        10.      * @version  1.0  
        11.      * @datetime 2012-11-30上午10:35:54  
        12.      * @comments  
        13.      */  
        14.     public class ExportDB {  
        15.       
        16.         /**  
        17.          * @param args  
        18.          */  
        19.         public static void main(String[] args) {  
        20.             // TODO Auto-generated method stub  
        21.               
        22.             //读取配置文件上面的信息  
        23.             Configuration cfg = new Configuration().configure();  
        24.               
        25.             //将配置文件写成ddl.  
        26.             SchemaExport export = new SchemaExport(cfg);  
        27.               
        28.             //将ddl打印大控制台并写入数据库中.  
        29.             export.create(true, true);  
        30.         }  
        31.       
        32.     }  


      • 测试打印数据:

      log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

      log4j:WARN Please initialize the log4j system properly.

      drop table if exists User

      create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime datetime, expireTime datetime, primary key (id))

      • 查看数据库中的表:
      • 建立客户端Client,添加用户数据到Mysql.
        • 建立client

      [html]  view plain copy print ?
      1. package com.tgb.hibernate;  
      2.       
      3.     import java.util.Date;  
      4.     import org.hibernate.Session;  
      5.     import org.hibernate.SessionFactory;  
      6.     import org.hibernate.cfg.Configuration;  
      7.       
      8.     /**  
      9.      * 客户端程序  
      10.      * @author   jnqqls  
      11.      * @group    TGB  
      12.      * @version  1.0  
      13.      * @datetime 2012-11-27上午9:31:32  
      14.      * @comments  
      15.      */  
      16.       
      17.     public class Client {  
      18.       
      19.         /**  
      20.          * @param args  
      21.          */  
      22.         public static void main(String[] args) {  
      23.             // 读取hibernate.cfg.xml文件  
      24.             Configuration cfg = new Configuration().configure();  
      25.       
      26.             // 建立SessionFactory,对应一个数据库的镜像.  
      27.             SessionFactory factory = cfg.buildSessionFactory();  
      28.       
      29.             // 获得session  
      30.             Session session = null;  
      31.       
      32.             try {  
      33.                 // 工厂创建session,并获得.  
      34.                 session = factory.openSession();  
      35.       
      36.                 // 手动开启事务  
      37.                 session.beginTransaction();  
      38.       
      39.                     // 创建User实体  
      40.                 User user = new User();  
      41.                 user.setName("jnqqls");  
      42.                 user.setPassword("jnqqls");  
      43.                 user.setCreateTime(new Date());  
      44.                 user.setExpireTime(new Date());  
      45.       
      46.                 // 保存user对象  
      47.                 session.save(user);  
      48.       
      49.                 // 提交事务  
      50.                 session.getTransaction().commit();  
      51.             } catch (Exception e) {  
      52.                 // 这里只是简单打印一下堆栈,用于测试  
      53.                 e.printStackTrace();  
      54.                     //事务回滚.  
      55.                 session.getTransaction().rollback();  
      56.             } finally {  
      57.       
      58.                 // session是否为null  
      59.                 if (session != null) {  
      60.       
      61.                     // session是否打开  
      62.                     if (session.isOpen()) {  
      63.       
      64.                         // 关闭session  
      65.                         session.close();  
      66.                     }  
      67.                 }  
      68.             }  
      69.       


        • 执行客户端程序.
          • console上打印的内容如下:

        [sql]  view plain copy print ?
        1. Hibernate:  
        2.      insert  
        3.      into  
        4.          User  
        5.          (namepassword, createTime, expireTime, id)  
        6.      values  
        7.          (?, ?, ?, ?, ?)  


         

        • 查看数据库



            总结:使用Hibernate可以让我们通过面向对象的思维来操作关系型数据库.并且在此文的实例中也有体现出在上一篇文章所谈到的Hibernate优点,例如原来插入数据的insert语句(console所打印的语句)现在只需要一句session.save(user)变能完成相同的功能.至此本文从Hibernate如何使用的角度介绍完毕,在接下来的文章中会继续对Hibernate中的内容进行学习和分享.


      你可能感兴趣的:(SSH)