Home > Database > Mysql Tutorial > Hibernate框架基础

Hibernate框架基础

WBOY
Release: 2016-06-07 14:50:00
Original
947 people have browsed it

ORM概念 O, Object 对象R, Realtion 关系 (关系型数据库: MySQL, Oracle…)M,Mapping 映射ORM, 对象关系映射!ORM, 解决什么问题? 存储: 能否把对象的数据直接保存到数据库? 获取: 能否直接从数据库拿到一个对象?想做到上面2点,必须要有映射!总结:

ORM概念

<code>O,  Object  对象
R, Realtion 关系  (关系型数据库: MySQL, Oracle…)
M,Mapping  映射

ORM, 对象关系映射!

ORM, 解决什么问题?
    存储:   能否把对象的数据直接保存到数据库? 
获取:  能否直接从数据库拿到一个对象?
想做到上面2点,必须要有映射!


总结:
    Hibernate与ORM的关系?
       Hibernate是ORM的实现!
</code>
Copy after login

Hibernate 案例

<code>搭建一个Hibernate环境,开发步骤:
1. 下载源码
        版本:hibernate-distribution-3.6.0.Final
2. 引入jar文件
        hibernate3.jar核心  +  required 必须引入的(6个) +  jpa 目录  + 数据库驱动包
3. 写对象以及对象的映射
        Employee.java            对象
        Employee.hbm.xml         对象的映射 (映射文件)
4. src/hibernate.cfg.xml  主配置文件
         数据库连接配置
         加载所用的映射(*.hbm.xml)
5. App.java  测试
</code>
Copy after login

对象      Employee.java

<code class=" hljs cs"><span class="hljs-comment">//一、 对象</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Employee {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> empId;
    <span class="hljs-keyword">private</span> String empName;
    <span class="hljs-keyword">private</span> Date workDate;

}
</code>
Copy after login

对象的映射 Employee.hbm.xml

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.a_hello"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"Employee"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"employee"</span>></span>

        <span class="hljs-comment"><!-- 主键 ,映射--></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"empId"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"id"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"native"</span>/></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>

        <span class="hljs-comment"><!-- 非主键,映射 --></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"empName"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"empName"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"workDate"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"workDate"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>

    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>

<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span>
</code>
Copy after login

主配置文件 hibernate.cfg.xml

<code class=" hljs xml"><span class="hljs-doctype"><!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-configuration</span>></span>
    <span class="hljs-tag"><<span class="hljs-title">session-factory</span>></span>
        <span class="hljs-comment"><!-- 数据库连接配置 --></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"hibernate.connection.driver_class"</span>></span>com.mysql.jdbc.Driver<span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"hibernate.connection.url"</span>></span>jdbc:mysql:///hib_demo<span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"hibernate.connection.username"</span>></span>root<span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"hibernate.connection.password"</span>></span>root<span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"hibernate.dialect"</span>></span>org.hibernate.dialect.MySQL5Dialect<span class="hljs-tag"></<span class="hljs-title">property</span>></span>

        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"hibernate.show_sql"</span>></span>true<span class="hljs-tag"></<span class="hljs-title">property</span>></span>

        <span class="hljs-comment"><!-- 加载所有映射 --></span>
        <span class="hljs-tag"><<span class="hljs-title">mapping</span> <span class="hljs-attribute">resource</span>=<span class="hljs-value">"cn/itcast/a_hello/Employee.hbm.xml"</span>/></span>
    <span class="hljs-tag"></<span class="hljs-title">session-factory</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-configuration</span>></span>
</code>
Copy after login

测试类 App.java

<code class=" hljs java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> {</span>

    <span class="hljs-annotation">@Test</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testHello</span>() <span class="hljs-keyword">throws</span> Exception {
        <span class="hljs-comment">// 对象</span>
        Employee emp = <span class="hljs-keyword">new</span> Employee();
        emp.setEmpName(<span class="hljs-string">"班长"</span>);
        emp.setWorkDate(<span class="hljs-keyword">new</span> Date());

        <span class="hljs-comment">// 获取加载配置文件的管理类对象</span>
        Configuration config = <span class="hljs-keyword">new</span> Configuration();
        config.configure();  <span class="hljs-comment">// 默认加载src/hibenrate.cfg.xml文件</span>
        <span class="hljs-comment">// 创建session的工厂对象</span>
        SessionFactory sf = config.buildSessionFactory();
        <span class="hljs-comment">// 创建session (代表一个会话,与数据库连接的会话)</span>
        Session session = sf.openSession();
        <span class="hljs-comment">// 开启事务</span>
        Transaction tx = session.beginTransaction();
        <span class="hljs-comment">//保存-数据库</span>
        session.save(emp);
        <span class="hljs-comment">// 提交事务</span>
        tx.commit();
        <span class="hljs-comment">// 关闭</span>
        session.close();
        sf.close();
    }
}
</code>
Copy after login

Hibernate Api

<code>|-- Configuration       配置管理类对象
    config.configure();    加载主配置文件的方法(hibernate.cfg.xml)
                           默认加载src/hibernate.cfg.xml
    config.configure(“cn/config/hibernate.cfg.xml”);   
                           加载指定路径下指定名称的主配置文件
    config.buildSessionFactory();   创建session的工厂对象

|-- SessionFactory    session的工厂(或者说代表了这个hibernate.cfg.xml配置文件)
    sf.openSession();        创建一个sesison对象
    sf.getCurrentSession();  创建session或取出session对象

|--Session       session对象维护了一个连接(Connection), 代表了与数据库连接的会话。
               Hibernate最重要的对象: 只用使用hibernate与数据库操作,都用到这个对象
        session.beginTransaction(); 开启一个事务; hibernate要求所有的与数据库的操作必须有事务的环境,否则报错!

    更新:
        session.save(obj);   保存一个对象
        session.update(emp);  更新一个对象
        session.saveOrUpdate(emp);  保存或者更新的方法:
                                    没有设置主键,执行保存;
        有设置主键,执行更新操作; 
        如果设置主键不存在报错!

    主键查询:
        session.get(Employee.class, 1);    主键查询
        session.load(Employee.class, 1);   主键查询 (支持懒加载)

    HQL查询:
        HQL查询与SQL查询区别:
            SQL: (结构化查询语句)查询的是表以及字段;  不区分大小写。
            HQL: hibernate  query  language 即hibernate提供的面向对象的查询语言
                查询的是对象以及对象的属性。
                区分大小写。

    Criteria查询:
         完全面向对象的查询。

    本地SQL查询:
        复杂的查询,就要使用原生态的sql查询,也可以,就是本地sql查询的支持!
        (缺点: 不能跨数据库平台!)

|-- Transaction    hibernate事务对象


共性问题1:
ClassNotFoundException…., 缺少jar文件!
共性问题2:
    如果程序执行程序,hibernate也有生成sql语句,但数据没有结果影响。
    问题一般是事务忘记提交…….
遇到问题,一定看错误提示!
</code>
Copy after login

Hibernate crud

<code class=" hljs java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeDaoImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IEmployeeDao</span>{</span>

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> Employee <span class="hljs-title">findById</span>(Serializable id) {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">// 获取Session</span>
            session = HibernateUtils.getSession();
            <span class="hljs-comment">// 开启事务</span>
            tx = session.beginTransaction();
            <span class="hljs-comment">// 主键查询</span>
            <span class="hljs-keyword">return</span> (Employee) session.get(Employee.class, id);
        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> List<Employee> <span class="hljs-title">getAll</span>() {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            <span class="hljs-comment">// HQL查询</span>
            Query q = session.createQuery(<span class="hljs-string">"from Employee"</span>);
            <span class="hljs-keyword">return</span> q.list();
        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> List<Employee> <span class="hljs-title">getAll</span>(String employeeName) {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query q =session.createQuery(<span class="hljs-string">"from Employee where empName=?"</span>);
            <span class="hljs-comment">// 注意:参数索引从0开始</span>
            q.setParameter(<span class="hljs-number">0</span>, employeeName);
            <span class="hljs-comment">// 执行查询</span>
            <span class="hljs-keyword">return</span> q.list();
        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> List<Employee> <span class="hljs-title">getAll</span>(<span class="hljs-keyword">int</span> index, <span class="hljs-keyword">int</span> count) {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query q = session.createQuery(<span class="hljs-string">"from Employee"</span>);
            <span class="hljs-comment">// 设置分页参数</span>
            q.setFirstResult(index);  <span class="hljs-comment">// 查询的其实行 </span>
            q.setMaxResults(count);   <span class="hljs-comment">// 查询返回的行数</span>

            List<Employee> list = q.list();
            <span class="hljs-keyword">return</span> list;
        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">save</span>(Employee emp) {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            <span class="hljs-comment">// 执行保存操作</span>
            session.save(emp);
        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }

    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">update</span>(Employee emp) {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            session.update(emp);

        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }

    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delete</span>(Serializable id) {
        Session session = <span class="hljs-keyword">null</span>;
        Transaction tx = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            <span class="hljs-comment">// 先根据id查询对象,再判断删除</span>
            Object obj = session.get(Employee.class, id);
            <span class="hljs-keyword">if</span> (obj != <span class="hljs-keyword">null</span>) {
                session.delete(obj);
            }
        } <span class="hljs-keyword">catch</span> (Exception e) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(e);
        } <span class="hljs-keyword">finally</span> {
            tx.commit();
            session.close();
        }
    }
}</code>
Copy after login

Hibernate.cfg.xml 主配置

<code>Hibernate.cfg.xml
    主配置文件中主要配置:数据库连接信息、其他参数、映射信息!

常用配置查看源码:
    hibernate-distribution-3.6.0.Final\project\etc\hibernate.properties
</code>
Copy after login

数据库连接参数配置

<code>例如:
## MySQL

#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password
</code>
Copy after login

自动建表

Hibernate.properties

<code>#hibernate.hbm2ddl.auto create-drop 每次在创建sessionFactory时候执行创建表;
                                当调用sesisonFactory的close方法的时候,删除表!
#hibernate.hbm2ddl.auto create   每次都重新建表; 如果表已经存在就先删除再创建
#hibernate.hbm2ddl.auto update  如果表不存在就创建; 表存在就不创建;
#hibernate.hbm2ddl.auto validate  (生成环境时候) 执行验证: 当映射文件的内容与数据库表结构不一样的时候就报错!
</code>
Copy after login

代码自动建表

<code class=" hljs java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App_ddl</span> {</span>

    <span class="hljs-comment">// 自动建表</span>
    <span class="hljs-annotation">@Test</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testCreate</span>() <span class="hljs-keyword">throws</span> Exception {
        <span class="hljs-comment">// 创建配置管理类对象</span>
        Configuration config = <span class="hljs-keyword">new</span> Configuration();
        <span class="hljs-comment">// 加载主配置文件</span>
        config.configure();

        <span class="hljs-comment">// 创建工具类对象</span>
        SchemaExport export = <span class="hljs-keyword">new</span> SchemaExport(config);
        <span class="hljs-comment">// 建表</span>
        <span class="hljs-comment">// 第一个参数: 是否在控制台打印建表语句</span>
        <span class="hljs-comment">// 第二个参数: 是否执行脚本</span>
        export.create(<span class="hljs-keyword">true</span>, <span class="hljs-keyword">true</span>);
    }
}
</code>
Copy after login

映射配置

<code>1. 普通字段类型
2. 主键映射
    单列主键映射
    多列作为主键映射

主键生成策略,查看api:   5.1.2.2.1. Various additional generators


数据库:
    一个表能否有多个主键?   不能。
    为什么要设置主键?       数据库存储的数据都是有效的,必须保持唯一。

    (为什么把id作为主键?)
        因为表中通常找不到合适的列作为唯一列即主键,所以为了方法用id列,因为id是数据库系统维护可以保证唯一,所以就把这列作为主键!

    联合/复合主键
    如果找不到合适的列作为主键,出来用id列以外,我们一般用联合主键,即多列的值作为一个主键,从而确保记录的唯一性。
</code>
Copy after login

映射配置

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>


<span class="hljs-comment"><!-- 映射文件: 映射一个实体类对象;  描述一个对象最终实现可以直接保存对象数据到数据库中。  --></span>
<span class="hljs-comment"><!-- 
    package: 要映射的对象所在的包(可选,如果不指定,此文件所有的类都要指定全路径)
    auto-import 默认为true, 在写hql的时候自动导入包名
                如果指定为false, 再写hql的时候必须要写上类的全名;
                  如:session.createQuery("from cn.itcast.c_hbm_config.Employee").list();
 --></span>
<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.c_hbm_config"</span> <span class="hljs-attribute">auto-import</span>=<span class="hljs-value">"true"</span>></span>

    <span class="hljs-comment"><!-- 
        class 映射某一个对象的(一般情况,一个对象写一个映射文件,即一个class节点)
            name 指定要映射的对象的类型
            table 指定对象对应的表;
                  如果没有指定表名,默认与对象名称一样 
     --></span>
    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"Employee"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"employee"</span>></span>

        <span class="hljs-comment"><!-- 主键 ,映射--></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"empId"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"id"</span>></span>
            <span class="hljs-comment"><!-- 
                主键的生成策略
                    identity  自增长(mysql,db2)
                    sequence  自增长(序列), oracle中自增长是以序列方法实现
                    native  自增长【会根据底层数据库自增长的方式选择identity或sequence】
                            如果是mysql数据库, 采用的自增长方式是identity
                            如果是oracle数据库, 使用sequence序列的方式实现自增长

                    increment  自增长(会有并发访问的问题,一般在服务器集群环境使用会存在问题。)

                    assigned  指定主键生成策略为手动指定主键的值
                    uuid      指定uuid随机生成的唯一的值
                    foreign   (外键的方式, one-to-one讲)
             --></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"uuid"</span>/></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>

        <span class="hljs-comment"><!-- 
            普通字段映射
            property
                name  指定对象的属性名称
                column 指定对象属性对应的表的字段名称,如果不写默认与对象属性一致。
                length 指定字符的长度, 默认为255
                type   指定映射表的字段的类型,如果不指定会匹配属性的类型
                    java类型:     必须写全名
                    hibernate类型:  直接写类型,都是小写
        --></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"empName"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"empName"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"java.lang.String"</span> <span class="hljs-attribute">length</span>=<span class="hljs-value">"20"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"workDate"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"java.util.Date"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-comment"><!-- 如果列名称为数据库关键字,需要用反引号或改列名。 --></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"desc"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"`desc`"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"java.lang.String"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>

    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>


<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span>

</code>
Copy after login

复合主键映射

对象与主键

<code class=" hljs java"><span class="hljs-comment">// 复合主键类</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CompositeKeys</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Serializable</span>{</span>
    <span class="hljs-keyword">private</span> String userName;
    <span class="hljs-keyword">private</span> String address;
   <span class="hljs-comment">// .. get/set</span>
}</code>
Copy after login
<code class=" hljs cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> User {
    <span class="hljs-comment">// 名字跟地址,不会重复</span>
    <span class="hljs-keyword">private</span> CompositeKeys keys;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;
}</code>
Copy after login

User.hbm.xml

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.d_compositeKey"</span> <span class="hljs-attribute">auto-import</span>=<span class="hljs-value">"true"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"User"</span>></span>

        <span class="hljs-comment"><!-- 复合主键映射 --></span>
        <span class="hljs-tag"><<span class="hljs-title">composite-id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"keys"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">key-property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"userName"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"string"</span>></span><span class="hljs-tag"></<span class="hljs-title">key-property</span>></span>

            <span class="hljs-tag"><<span class="hljs-title">key-property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"address"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"string"</span>></span><span class="hljs-tag"></<span class="hljs-title">key-property</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">composite-id</span>></span>

        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"age"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"int"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>     

    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span></code>
Copy after login

APP.java

<code class=" hljs cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> App2 {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> SessionFactory sf;
    <span class="hljs-keyword">static</span>  {       
        <span class="hljs-comment">// 创建sf对象</span>
        sf = <span class="hljs-keyword">new</span> Configuration()
            .configure()
            .addClass(User.class)  <span class="hljs-comment">//(测试) 会自动加载映射文件:Employee.hbm.xml</span>
            .buildSessionFactory();
    }

    <span class="hljs-comment">//1. 保存对象</span>
    @Test
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testSave</span>() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        <span class="hljs-comment">// 对象</span>
        CompositeKeys keys = <span class="hljs-keyword">new</span> CompositeKeys();
        keys.setAddress(<span class="hljs-string">"广州棠东"</span>);
        keys.setUserName(<span class="hljs-string">"Jack"</span>);
        User user = <span class="hljs-keyword">new</span> User();
        user.setAge(<span class="hljs-number">20</span>);
        user.setKeys(keys);

        <span class="hljs-comment">// 保存</span>
        session.save(user);


        tx.commit();
        session.close();
    }

    @Test
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testGet</span>() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        <span class="hljs-comment">//构建主键再查询</span>
        CompositeKeys keys = <span class="hljs-keyword">new</span> CompositeKeys();
        keys.setAddress(<span class="hljs-string">"广州棠东"</span>);
        keys.setUserName(<span class="hljs-string">"Jack"</span>);

        <span class="hljs-comment">// 主键查询</span>
        User user = (User) session.<span class="hljs-keyword">get</span>(User.class, keys);
        <span class="hljs-comment">// 测试输出</span>
        <span class="hljs-keyword">if</span> (user != <span class="hljs-keyword">null</span>){
            System.<span class="hljs-keyword">out</span>.println(user.getKeys().getUserName());
            System.<span class="hljs-keyword">out</span>.println(user.getKeys().getAddress());
            System.<span class="hljs-keyword">out</span>.println(user.getAge());
        }


        tx.commit();
        session.close();
    }
}

</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template