Hibernate(一)

1)建立实体类User.java
  
[java] view plain copy print?
package com.liang.hibernate;  
  
import java.util.Date;  
  
public class User {  
    private String id;  
    private String name;  
    private String password;  
    private Date createTime;  
    private Date expireTime;  
      
    public String getId() {  
        return id;  
    }  
    public void setId(String id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getPassword() {  
        return password;  
    }  
    public void setPassword(String password) {  
        this.password = password;  
    }  
    public Date getCreateTime() {  
        return createTime;  
    }  
    public void setCreateTime(Date createTime) {  
        this.createTime = createTime;  
    }  
    public Date getExpireTime() {  
        return expireTime;  
    }  
    public void setExpireTime(Date expireTime) {  
        this.expireTime = expireTime;  
    }  
  
}  
 
(2)提供User.hbm.xml文件,完成实体类映射
 
[html] view plain copy print?
<span style="font-size:12px;"><?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <!--生成默认为user的数据库表-->  
    <class name="com.liang.hibernate.User">  
        <id name="id">  
            <!-- 算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID -->  
            <generator class="uuid"></generator>  
        </id>  
        <property name="name"></property>  
        <property name="password"></property>  
        <property name="createTime" type="date"></property>  
        <property name="expireTime" type="date"></property>  
    </class>  
      
</hibernate-mapping></span>3)将User.hbm.xml文件加入到hibernate.cfg.xml文件中
 
[html] view plain copy print?
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
        <!-- 设置数据库URL -->  
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>  
        <!-- 数据库用户名 -->  
        <property name="hibernate.connection.username">root</property>  
        <!-- 数据库密码 -->  
        <property name="hibernate.connection.password">123456</property>  
        <!-- 指定对应数据库的方言,hibernate为了更好适配各种关系数据库,针对每种数据库都指定了一个方言dialect -->  
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
          
        <!-- 映射文件 -->  
        <mapping resource="com/liang/hibernate/User.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>4)编写工具类ExportDB.java,将hbm生成ddl,也就是hbm2ddl
 
[java] view plain copy print?
package com.liang.hibernate;  
  
import org.hibernate.cfg.Configuration;  
import org.hibernate.tool.hbm2ddl.SchemaExport;  
  
/** 
 * 将hbm生成ddl 
 * @author liang 
 * 
 */  
public class ExportDB{    
    public static void main(String[]args){  
        //默认读取hibernate.cfg.xml文件  
        Configuration cfg = new Configuration().configure();  
        ////生成并输出sql到文件(当前目录)和数据库  
        SchemaExport export = new SchemaExport(cfg);  
        export.create(true, true);  
    }  
}  
 
测试之前,要提前建立数据库hibernate_first,测试如下: 
 
控制台打印的SQL语句:
 
[sql] view plain copy print?
drop table if exists User  
create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime date, expireTime date, primary key (id))  
 
数据库表结构:
           
 
(5)建立客户端类Client,添加用户数据到mySQL
 
[java] view plain copy print?
package com.liang.hibernate;  
  
import java.util.Date;  
  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  
  
public class Client {  
    public static void main(String[]args){  
        //读取hibernate.cfg.xml文件  
        Configuration cfg = new Configuration().configure();  
        //建立SessionFactory  
        SessionFactory factory =cfg.buildSessionFactory();  
          
        //取得session  
        Session session = null;  
          
        try{  
            //开启session  
            session = factory.openSession();  
            //开启事务  
            session.beginTransaction();  
              
            User user = new User();  
            user.setName("jiuqiyuliang");  
            user.setPassword("123456");  
            user.setCreateTime(new Date());  
            user.setExpireTime(new Date());  
            //保存User对象  
            session.save(user);  
              
            //提交事务  
            session.getTransaction().commit();  
              
        }catch(Exception e){  
            e.printStackTrace();  
            //回滚事务  
            session.getTransaction().rollback();  
        }finally{  
            if(session != null){  
                if(session.isOpen()){  
                    //关闭session  
                    session.close();  
                }  
            }  
        }  
    }  
}  

右键debug运行,测试完成之后,我们查询一下测试结果:
            
 
5、为了在调试过程中能观察到Hibernate的日志输出,最好加入log4j.properties配置文件、在CLASSPATH中新建log4j.properties配置文件或将该配置文件拷贝到src下,便于程序调试。
内容如下:
 
[html] view plain copy print?
<span style="font-size:12px;">### direct log messages to stdout ###  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target=System.out  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  
### direct messages to file hibernate.log ###  
#log4j.appender.file=org.apache.log4j.FileAppender  
#log4j.appender.file.File=hibernate.log  
#log4j.appender.file.layout=org.apache.log4j.PatternLayout  
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  
### set log levels - for more verbose logging change 'info' to 'debug' ###  
  
log4j.rootLogger=warn, stdout</span>  
 
配置完成后,项目结构如下图所示:
 
          

 

posted @ 2017-09-24 10:19  呵呵哒12138  阅读(96)  评论(0编辑  收藏  举报