hibernate框架入门



1、在IDE中创建java项目(比较简单不再演示)

 

2、创建source folder,命名为Hibernate3,在Hibernate下载文件中找到我们所需要的三个配置文件和所有jar包,拷贝所需jar文件,构建依赖包

 

           

3、提供hibernate.cfg.xml文件,完成基本配置

 

4、写代码

 

(1)建立实体类User.java

  

[java]  view plain  copy
 print ?
  1. package com.liang.hibernate;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.     private String id;  
  7.     private String name;  
  8.     private String password;  
  9.     private Date createTime;  
  10.     private Date expireTime;  
  11.       
  12.     public String getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(String id) {  
  16.         this.id = id;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public String getPassword() {  
  25.         return password;  
  26.     }  
  27.     public void setPassword(String password) {  
  28.         this.password = password;  
  29.     }  
  30.     public Date getCreateTime() {  
  31.         return createTime;  
  32.     }  
  33.     public void setCreateTime(Date createTime) {  
  34.         this.createTime = createTime;  
  35.     }  
  36.     public Date getExpireTime() {  
  37.         return expireTime;  
  38.     }  
  39.     public void setExpireTime(Date expireTime) {  
  40.         this.expireTime = expireTime;  
  41.     }  
  42.   
  43. }  

 

(2)提供User.hbm.xml文件,完成实体类映射

 

[html]  view plain  copy
 print ?
  1. <span style="font-size:12px;"><?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <!--生成默认为user的数据库表-->  
  7.     <class name="com.liang.hibernate.User">  
  8.         <id name="id">  
  9.             <!-- 算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID -->  
  10.             <generator class="uuid"></generator>  
  11.         </id>  
  12.         <property name="name"></property>  
  13.         <property name="password"></property>  
  14.         <property name="createTime" type="date"></property>  
  15.         <property name="expireTime" type="date"></property>  
  16.     </class>  
  17.       
  18. </hibernate-mapping></span>  

 

(3)将User.hbm.xml文件加入到hibernate.cfg.xml文件中

 

[html]  view plain  copy
 print ?
  1. <!DOCTYPE hibernate-configuration PUBLIC  
  2.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  3.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <!-- 设置数据库驱动 -->  
  8.         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  9.         <!-- 设置数据库URL -->  
  10.         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>  
  11.         <!-- 数据库用户名 -->  
  12.         <property name="hibernate.connection.username">root</property>  
  13.         <!-- 数据库密码 -->  
  14.         <property name="hibernate.connection.password">123456</property>  
  15.         <!-- 指定对应数据库的方言,hibernate为了更好适配各种关系数据库,针对每种数据库都指定了一个方言dialect -->  
  16.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
  17.           
  18.         <!-- 映射文件 -->  
  19.         <mapping resource="com/liang/hibernate/User.hbm.xml"/>  
  20.     </session-factory>  
  21. </hibernate-configuration>  

 

(4)编写工具类ExportDB.java,将hbm生成ddl,也就是hbm2ddl

 

[java]  view plain  copy
 print ?
  1. package com.liang.hibernate;  
  2.   
  3. import org.hibernate.cfg.Configuration;  
  4. import org.hibernate.tool.hbm2ddl.SchemaExport;  
  5.   
  6. /** 
  7.  * 将hbm生成ddl 
  8.  * @author liang 
  9.  * 
  10.  */  
  11. public class ExportDB{    
  12.     public static void main(String[]args){  
  13.         //默认读取hibernate.cfg.xml文件  
  14.         Configuration cfg = new Configuration().configure();  
  15.         生成并输出sql到文件(当前目录)和数据库  
  16.         SchemaExport export = new SchemaExport(cfg);  
  17.         export.create(truetrue);  
  18.     }  
  19. }  

 

测试之前,要提前建立数据库hibernate_first,测试如下: 

 

控制台打印的SQL语句:

 

[sql]  view plain  copy
 print ?
  1. drop table if exists User  
  2. create table User (id varchar(255) not nullname varchar(255), password varchar(255), createTime date, expireTime dateprimary key (id))  

 

数据库表结构:

           

 

(5)建立客户端类Client,添加用户数据到mySQL

 

[java]  view plain  copy
 print ?
  1. package com.liang.hibernate;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.hibernate.cfg.Configuration;  
  8.   
  9. public class Client {  
  10.     public static void main(String[]args){  
  11.         //读取hibernate.cfg.xml文件  
  12.         Configuration cfg = new Configuration().configure();  
  13.         //建立SessionFactory  
  14.         SessionFactory factory =cfg.buildSessionFactory();  
  15.           
  16.         //取得session  
  17.         Session session = null;  
  18.           
  19.         try{  
  20.             //开启session  
  21.             session = factory.openSession();  
  22.             //开启事务  
  23.             session.beginTransaction();  
  24.               
  25.             User user = new User();  
  26.             user.setName("jiuqiyuliang");  
  27.             user.setPassword("123456");  
  28.             user.setCreateTime(new Date());  
  29.             user.setExpireTime(new Date());  
  30.             //保存User对象  
  31.             session.save(user);  
  32.               
  33.             //提交事务  
  34.             session.getTransaction().commit();  
  35.               
  36.         }catch(Exception e){  
  37.             e.printStackTrace();  
  38.             //回滚事务  
  39.             session.getTransaction().rollback();  
  40.         }finally{  
  41.             if(session != null){  
  42.                 if(session.isOpen()){  
  43.                     //关闭session  
  44.                     session.close();  
  45.                 }  
  46.             }  
  47.         }  
  48.     }  
  49. }  


右键debug运行,测试完成之后,我们查询一下测试结果:

            

 

5、为了在调试过程中能观察到Hibernate的日志输出,最好加入log4j.properties配置文件、在CLASSPATH中新建log4j.properties配置文件或将该配置文件拷贝到src下,便于程序调试。

内容如下:

 

[html]  view plain  copy
 print ?
  1. <span style="font-size:12px;">### direct log messages to stdout ###  
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  3. log4j.appender.stdout.Target=System.out  
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  6.   
  7. ### direct messages to file hibernate.log ###  
  8. #log4j.appender.file=org.apache.log4j.FileAppender  
  9. #log4j.appender.file.File=hibernate.log  
  10. #log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  11. #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  12.   
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###  
  14.   
  15. log4j.rootLogger=warn, stdout</span>  

 

配置完成后,项目结构如下图所示:

 

          


 

五、最后

 

      自己动手丰衣足食,实践出真理,纸上得来终觉浅,绝知此事要躬行。虽然这个实例非常简单,但是我们踏进了持久层框架的大门。

 

      从上面的简单实例可以看到,我们只是使用Hibernate对User这一个实体进行了映射,比较简单,但是完全不符合实际。如何像关系型数据库一样表示多种关联关系,例如:一对一,一对多,多对多等等,我们还需要深入。下篇博文,我们介绍Hibernate的基本映射原理以及关联关系映射。

1、在IDE中创建java项目(比较简单不再演示)

 

2、创建source folder,命名为Hibernate3,在Hibernate下载文件中找到我们所需要的三个配置文件和所有jar包,拷贝所需jar文件,构建依赖包

 

           

3、提供hibernate.cfg.xml文件,完成基本配置

 

4、写代码

 

(1)建立实体类User.java

  

[java]  view plain  copy
 print ?
  1. package com.liang.hibernate;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.     private String id;  
  7.     private String name;  
  8.     private String password;  
  9.     private Date createTime;  
  10.     private Date expireTime;  
  11.       
  12.     public String getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(String id) {  
  16.         this.id = id;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public String getPassword() {  
  25.         return password;  
  26.     }  
  27.     public void setPassword(String password) {  
  28.         this.password = password;  
  29.     }  
  30.     public Date getCreateTime() {  
  31.         return createTime;  
  32.     }  
  33.     public void setCreateTime(Date createTime) {  
  34.         this.createTime = createTime;  
  35.     }  
  36.     public Date getExpireTime() {  
  37.         return expireTime;  
  38.     }  
  39.     public void setExpireTime(Date expireTime) {  
  40.         this.expireTime = expireTime;  
  41.     }  
  42.   
  43. }  

 

(2)提供User.hbm.xml文件,完成实体类映射

 

[html]  view plain  copy
 print ?
  1. <span style="font-size:12px;"><?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <!--生成默认为user的数据库表-->  
  7.     <class name="com.liang.hibernate.User">  
  8.         <id name="id">  
  9.             <!-- 算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID -->  
  10.             <generator class="uuid"></generator>  
  11.         </id>  
  12.         <property name="name"></property>  
  13.         <property name="password"></property>  
  14.         <property name="createTime" type="date"></property>  
  15.         <property name="expireTime" type="date"></property>  
  16.     </class>  
  17.       
  18. </hibernate-mapping></span>  

 

(3)将User.hbm.xml文件加入到hibernate.cfg.xml文件中

 

[html]  view plain  copy
 print ?
  1. <!DOCTYPE hibernate-configuration PUBLIC  
  2.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  3.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <!-- 设置数据库驱动 -->  
  8.         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  9.         <!-- 设置数据库URL -->  
  10.         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>  
  11.         <!-- 数据库用户名 -->  
  12.         <property name="hibernate.connection.username">root</property>  
  13.         <!-- 数据库密码 -->  
  14.         <property name="hibernate.connection.password">123456</property>  
  15.         <!-- 指定对应数据库的方言,hibernate为了更好适配各种关系数据库,针对每种数据库都指定了一个方言dialect -->  
  16.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
  17.           
  18.         <!-- 映射文件 -->  
  19.         <mapping resource="com/liang/hibernate/User.hbm.xml"/>  
  20.     </session-factory>  
  21. </hibernate-configuration>  

 

(4)编写工具类ExportDB.java,将hbm生成ddl,也就是hbm2ddl

 

[java]  view plain  copy
 print ?
  1. package com.liang.hibernate;  
  2.   
  3. import org.hibernate.cfg.Configuration;  
  4. import org.hibernate.tool.hbm2ddl.SchemaExport;  
  5.   
  6. /** 
  7.  * 将hbm生成ddl 
  8.  * @author liang 
  9.  * 
  10.  */  
  11. public class ExportDB{    
  12.     public static void main(String[]args){  
  13.         //默认读取hibernate.cfg.xml文件  
  14.         Configuration cfg = new Configuration().configure();  
  15.         生成并输出sql到文件(当前目录)和数据库  
  16.         SchemaExport export = new SchemaExport(cfg);  
  17.         export.create(truetrue);  
  18.     }  
  19. }  

 

测试之前,要提前建立数据库hibernate_first,测试如下: 

 

控制台打印的SQL语句:

 

[sql]  view plain  copy
 print ?
  1. drop table if exists User  
  2. create table User (id varchar(255) not nullname varchar(255), password varchar(255), createTime date, expireTime dateprimary key (id))  

 

数据库表结构:

           

 

(5)建立客户端类Client,添加用户数据到mySQL

 

[java]  view plain  copy
 print ?
  1. package com.liang.hibernate;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.hibernate.cfg.Configuration;  
  8.   
  9. public class Client {  
  10.     public static void main(String[]args){  
  11.         //读取hibernate.cfg.xml文件  
  12.         Configuration cfg = new Configuration().configure();  
  13.         //建立SessionFactory  
  14.         SessionFactory factory =cfg.buildSessionFactory();  
  15.           
  16.         //取得session  
  17.         Session session = null;  
  18.           
  19.         try{  
  20.             //开启session  
  21.             session = factory.openSession();  
  22.             //开启事务  
  23.             session.beginTransaction();  
  24.               
  25.             User user = new User();  
  26.             user.setName("jiuqiyuliang");  
  27.             user.setPassword("123456");  
  28.             user.setCreateTime(new Date());  
  29.             user.setExpireTime(new Date());  
  30.             //保存User对象  
  31.             session.save(user);  
  32.               
  33.             //提交事务  
  34.             session.getTransaction().commit();  
  35.               
  36.         }catch(Exception e){  
  37.             e.printStackTrace();  
  38.             //回滚事务  
  39.             session.getTransaction().rollback();  
  40.         }finally{  
  41.             if(session != null){  
  42.                 if(session.isOpen()){  
  43.                     //关闭session  
  44.                     session.close();  
  45.                 }  
  46.             }  
  47.         }  
  48.     }  
  49. }  


右键debug运行,测试完成之后,我们查询一下测试结果:

            

 

5、为了在调试过程中能观察到Hibernate的日志输出,最好加入log4j.properties配置文件、在CLASSPATH中新建log4j.properties配置文件或将该配置文件拷贝到src下,便于程序调试。

内容如下:

 

[html]  view plain  copy
 print ?
  1. <span style="font-size:12px;">### direct log messages to stdout ###  
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  3. log4j.appender.stdout.Target=System.out  
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  6.   
  7. ### direct messages to file hibernate.log ###  
  8. #log4j.appender.file=org.apache.log4j.FileAppender  
  9. #log4j.appender.file.File=hibernate.log  
  10. #log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  11. #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
  12.   
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###  
  14.   
  15. log4j.rootLogger=warn, stdout</span>  

 

配置完成后,项目结构如下图所示:

 

          


 

五、最后

 

      自己动手丰衣足食,实践出真理,纸上得来终觉浅,绝知此事要躬行。虽然这个实例非常简单,但是我们踏进了持久层框架的大门。

 

      从上面的简单实例可以看到,我们只是使用Hibernate对User这一个实体进行了映射,比较简单,但是完全不符合实际。如何像关系型数据库一样表示多种关联关系,例如:一对一,一对多,多对多等等,我们还需要深入。下篇博文,我们介绍Hibernate的基本映射原理以及关联关系映射。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值