欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate:对象关联关系映射

程序员文章站 2022-06-13 21:50:05
...

 

       Hibernate实现对象与关系之间的映射,通过对对象的操作实现关系的存储,在数据库中实体之间可能会有一定的联系,例如在通用权限管理系统中会有用户和角色实体,用户和角色之间具有一定的联系,即用户拥有一定的角色,所以数据库中会出现3个表,用户表,角色表,用户角色表。其中用户角色表中存在一定的约束,主键分别是用户表和角色表的外键,用户角色表中的用户id必须来自用户表。在使用Hibernate实现时可以使用三个对象来分别对应三张表,但这样对象之间就缺乏了这种关联信息,而且不能保证这种约束关系,为了实现这种约束,Hibernate使用了对象关联关系映射。

1)首先配置hibernate配置文件,包括两个对象关系映射文件,分别对应两个类,用户和角色:

<hibernate-configuration>
    <session-factory >

        <!-- local connection properties -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/example</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">mzuser</property>
        <property name="hibernate.connection.password">123456</property>
        <!-- property name="hibernate.connection.pool_size"></property -->

        <!-- dialect for MySQL -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <mapping resource="com/mz/bean/UserBean.hbm.xml"/>        
        <mapping resource="com/mz/bean/RoleBean.hbm.xml"/>              //对象关系映射配置文件
    </session-factory>
</hibernate-configuration>

2)数据库中有三张表,用户、角色和用户角色表:

mysql> desc CmsUser;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| userid   | int(8)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(20) | NO   | UNI | NULL    |                |
| password | varchar(20) | YES  |     | NULL    |                |
| area     | varchar(10) | YES  |     | NULL    |                |
| deptrole | varchar(10) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mysql> desc CmsRole;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| roleid   | int(8)      | NO   | PRI | NULL    | auto_increment |
| rolename | varchar(20) | NO   | UNI | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

 

mysql> desc CmsUserRole;
+--------+--------+------+-----+---------+-------+
| Field  | Type   | Null | Key | Default | Extra |
+--------+--------+------+-----+---------+-------+
| userid | int(8) | NO   | PRI | 0       |       |
| roleid | int(8) | NO   | PRI | 0       |       |
+--------+--------+------+-----+---------+-------+
2 rows in set (0.00 sec)

 3)用户和角色两个类的定义,用户和角色属于多对多的关系,即一个用户可以具有多个角色,一个角色也可以被多个用户拥有,为了表示用户和角色的这种关联,在用户类中定义一个集合,表示用户拥有多个角色,对应到关系中的用户角色表:

package com.mz.bean;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by hadoop on 15-9-9.
 */
public class UserBean {
    private int userId;
    private String userName;
    private String password;
    private String area;
    private String deptRole;
    private Set<RoleBean> roles = new HashSet<RoleBean>();

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userid) {
        this.userId = userid;
    }

    public String getUserName() { return userName; }

    public void setUserName(String username) {
        this.userName = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getDeptRole() {
        return deptRole;
    }

    public void setDeptRole(String deptrole) {
        this.deptRole = deptrole;
    }

    public Set<RoleBean> getRoles() {
        return roles;
    }

    public void setRoles(Set<RoleBean> roles) {
        this.roles = roles;
    }
}

 

package com.mz.bean;

/**
 * Created by hadoop on 15-9-14.
 */
public class RoleBean {
    private int roleId;
    private String roleName;

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}

 4)对象关系映射配置文件

<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.mz.bean">
    <class name="com.mz.bean.UserBean" table="CmsUser">
        <id name="userId" type="int">
            <column name="userid"></column>
            <generator class="increment"/>
        </id>
        <property name="userName" type="java.lang.String">
            <column name="username" length="20"></column>
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="20"></column>
        </property>
        <property name="area" type="java.lang.String">
            <column name="area" length="10"></column>
        </property>
        <property name="deptRole" type="java.lang.String">
            <column name="deptrole" length="10"></column>
        </property>
        <!--对象关联关系映射-->
        <set name="roles" table="CmsUserRole">
            <key column="userid"></key>
            <many-to-many column="roleid" class="com.mz.bean.RoleBean" unique="true"/>
        </set>
    </class>

</hibernate-mapping>

 

<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.mz.bean">
    <class name="com.mz.bean.RoleBean" table="CmsRole">
        <id name="roleId" type="int">
            <column name="roleid"></column>
            <generator class="increment"/>
        </id>
        <property name="roleName" type="java.lang.String">
            <column name="rolename" length="20"></column>
        </property>
    </class>

</hibernate-mapping>

 5)测试类:创建多个用户对象和角色对象,并在用户对象中加入拥有角色的集合,最后save()用户和角色对象。

 @Test
    public void testMMMap(){
        UserBean userBean1 = new UserBean();
        UserBean userBean2 = new UserBean();
        RoleBean roleBean1 = new RoleBean();
        RoleBean roleBean2 = new RoleBean();
        RoleBean roleBean3 = new RoleBean();

        userBean1.setUserName("admin1");
        userBean1.setPassword("123456");
        userBean2.setUserName("normal");
        userBean2.setPassword("123456");
        roleBean1.setRoleName("admin");
        roleBean2.setRoleName("commerce");
        roleBean3.setRoleName("finance");
        userBean1.getRoles().add(roleBean1);
        userBean1.getRoles().add(roleBean2);
        userBean2.getRoles().add(roleBean1);
        userBean2.getRoles().add(roleBean3);
        Session session = SessionUtil.getSession();
        org.hibernate.Transaction ta = session.beginTransaction();
        session.save(userBean1);
        session.save(userBean2);
        session.save(roleBean1);
        session.save(roleBean2);
        session.save(roleBean3);
        ta.commit();
        SessionUtil.closeSession();
    }

6) 结果查询:查询数据库发现三张表中都插入了新的数据,其中用户角色表中有用户关系与角色关系的联系。

mysql> select * from CmsUser;
+--------+----------+----------+------+----------+
| userid | username | password | area | deptrole |
+--------+----------+----------+------+----------+
|      1 | admin1   | 123456   | NULL | NULL     |
|      2 | normal   | 123456   | NULL | NULL     |
+--------+----------+----------+------+----------+
2 rows in set (0.00 sec)

mysql> select * from CmsRole;
+--------+----------+
| roleid | rolename |
+--------+----------+
|      1 | admin    |
|      2 | commerce |
|      3 | finance  |
+--------+----------+
3 rows in set (0.00 sec)

mysql> select * from CmsUserRole;
+--------+--------+
| userid | roleid |
+--------+--------+
|      1 |      1 |
|      2 |      1 |
|      1 |      2 |
|      2 |      3 |
+--------+--------+
4 rows in set (0.00 sec)