zoukankan      html  css  js  c++  java
  • (Hibernate进阶)Hibernate基本映射(三)

    介绍Hibernate的经典内容:对象关系映射。主要介绍映射的基本概念,映射的分类,映射文件。

    概念

           ORM(Object Relational Mapping),即对象关系映射。它的作用就是在关系型数据库和对象之间做了一个映射。从对象(Object)映射到关系(Relation),再从关系映射到对象。相信很多人跟小编一个毛病,看到概念就头疼,下面小编画了一张图加深理解。

        

             这张图特别简单:原来,没有Hibernate时,我们需要通过JDBC+手动写SQL语句来操作数据库,现在,有了Hibernate,它将JDBC+SQL进行了高度封装,我们不需要再去和复杂SQL打交道,只要像操作对象一样操作数据库就可以了。

     

           ORM的实现思想就是将数据库中表的数据映射成对象,Hibernate可以使我们采用对象化的思维操作关系型数据库。

    映射文件

     Hibernate在实现ORM功能的时候主要用到的文件有:
        1、 映射类(*.Java):它是描述数据库表的结构,表中的字段在类中被描述成属性,将来就可以实现把表中的记录映射成为该类的对象了。
     
        2、映射文件(*.hbm.xml):它是指定数据库表和映射类之间的关系,包括映射类和数据库表的对应关系、表字段和类属性类型的对应关系以及表字段和类属性名称的对应关系等。
     
        3、 hibernate核心配置文件(*.properties/*.cfg.xml):它指定hibernate的一些核心配置,包含与数据库连接时需要的连接信息,比如连接哪种数据库、登录数据库的用户名、登录密码以及连接字符串等。映射文件的地址信息也放在这里。

    分类

               

          上面的内容看上去挺多,其实特别少,基本映射很简单,我们主要学习关联关系映射,其他几种映射一般不会用,只需要了解即可,用的时候看一下相关资料会做就好。

     基本映射

              上篇博文我们已经实现了一个基本映射,是使用XML方式配置映射,如下所示:

    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.     <class name="com.liang.hibernate.User" >  
    7.         <id name="id">  
    8.             <!-- 算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID -->  
    9.             <generator class="uuid"></generator>  
    10.         </id>  
    11.         <property name="name"></property>  
    12.         <property name="password"></property>  
    13.         <property name="createTime" type="date"></property>  
    14.         <property name="expireTime" type="date"></property>  
    15.     </class>  
    16. </hibernate-mapping></span>  

     

    除了XML方式配置映射外,还可以通过给类文件添加注解的方式配置映射,在上篇博文的基础之上,我们稍加修改。

     

    1、加入hibernate annotion支持包

          *hibernate-annotations.jar
          *hibernate-commons-annotations.jar
          *ejb3-persistence.jar

     

     如图所示:

              

    2、建立实体类User,采用注解完成映射

    1. package com.liang.hibernate;  
    2.   
    3. import java.util.Date;  
    4.   
    5. import javax.persistence.Column;  
    6. import javax.persistence.Entity;  
    7. import javax.persistence.GeneratedValue;  
    8. import javax.persistence.GenerationType;  
    9. import javax.persistence.Id;  
    10. import javax.persistence.Temporal;  
    11. import javax.persistence.TemporalType;  
    12.   
    13. @Entity //不写Table默认为user,@Table(name="t_user")  
    14. public class User {  
    15.   
    16.     @Id //主键  
    17.     @GeneratedValue(strategy=GenerationType.AUTO)//采用数据库自增方式生成主键  
    18.     //JPA提供的四种标准用法为TABLE,SEQUENCE,IDENTITY,AUTO.   
    19.     //TABLE:使用一个特定的数据库表格来保存主键。   
    20.     //SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。   
    21.     //IDENTITY:主键由数据库自动生成(主要是自动增长型)   
    22.     //AUTO:主键由程序控制。  
    23.     private int id;  
    24.       
    25.     private String name;  
    26.     private String password;  
    27.       
    28.     @Temporal(TemporalType.DATE)//生成yyyy-MM-dd类型的日期  
    29.     private Date createTime;  
    30.     @Temporal(TemporalType.DATE)//生成yyyy-MM-dd类型的日期  
    31.     private Date expireTime;  
    32.       
    33.       
    34.   
    35.     public int getId() {  
    36.         return id;  
    37.     }  
    38.     public void setId(int id) {  
    39.         this.id = id;  
    40.     }  
    41.     @Column(name="name",unique=true,nullable=false) //字段为name,不允许为空,用户名唯一  
    42.     public String getName() {  
    43.         return name;  
    44.     }  
    45.     public void setName(String name) {  
    46.         this.name = name;  
    47.     }  
    48.     public String getPassword() {  
    49.         return password;  
    50.     }  
    51.     public void setPassword(String password) {  
    52.         this.password = password;  
    53.     }  
    54.     public Date getCreateTime() {  
    55.         return createTime;  
    56.     }  
    57.     public void setCreateTime(Date createTime) {  
    58.         this.createTime = createTime;  
    59.     }  
    60.     public Date getExpireTime() {  
    61.         return expireTime;  
    62.     }  
    63.     public void setExpireTime(Date expireTime) {  
    64.         this.expireTime = expireTime;  
    65.     }  
    66.   
    67. }  

    注:由于主键改成了自增长,所以数据类型修改成了int类型

    3、提供hibernate.cfg.xml文件,将实体类User加入到hibernate.cfg.xml配置文件中,完成基本配置

    1. <span style="font-size:12px;"><!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.         <!-- mysql的方言 -->  
    16.         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
    17.           
    18.         <!-- 映射文件 -->  
    19.         <!--  <mapping resource="com/liang/hibernate/User.hbm.xml"/>  -->    
    20.           
    21.         <!-- 由原来的映射文件,改成实体类 -->  
    22.         <mapping class="com.liang.hibernate.User"/>  
    23.           
    24.     </session-factory>  
    25. </hibernate-configuration></span>  

    4、编写工具类ExportDB.java,注解生成ddl,必须采用AnnotationConfiguration类

    1. <span style="font-size:12px;">package com.liang.hibernate;  
    2.   
    3. import org.hibernate.cfg.AnnotationConfiguration;  
    4. import org.hibernate.cfg.Configuration;  
    5. import org.hibernate.tool.hbm2ddl.SchemaExport;  
    6.   
    7. /** 
    8.  * 将hbm生成ddl 
    9.  * @author liang 
    10.  * 
    11.  */  
    12. public class ExportDB{    
    13.     public static void main(String[]args){  
    14.         //默认读取hibernate.cfg.xml文件  
    15.         Configuration cfg = new AnnotationConfiguration().configure();  
    16.         SchemaExport export = new SchemaExport(cfg);  
    17.         export.create(true, true);  
    18.     }  
    19. }</span>  

    数据库生成表如图所示:

         



    5、建立客户端类Client,添加用户数据到MySQL

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

     运行之后,数据库表生成的数据,如下图所示:

          

       转:http://blog.csdn.net/jiuqiyuliang/article/details/40153905

      

  • 相关阅读:
    shell 函数用法
    shell read变量的读入
    利用系统函数模拟实现nginx 系统脚本启动的特殊颜色专业效果
    shell重定向介绍及使用
    监控MySQL或Web服务是否正常
    centos 6.5下安装nmap工具及简单用法
    if条件简单语法
    shell 的条件表达式及逻辑操作符简单介绍
    mysql常见的错误代码
    Linux MySql 安装与配置(二进制包)
  • 原文地址:https://www.cnblogs.com/xijin-wu/p/6085577.html
Copyright © 2011-2022 走看看