hibernate多对多关联映射

关联是类(类的实例)之间的关系,表示有意义和值得关注的连接。

本系列将介绍Hibernate中主要的几种关联映射

Hibernate一对一主键单向关联
Hibernate一对一主键双向关联
Hibernate一对一外键单向关联
Hibernate一对一外键双向关联
Hibernate多对一单向关联
Hibernate多对一双向关联

Hibernate多对多关联

代码都写有注释,主要包括(核心配置文件,实体映射文件,实体类,测试类,数据库)主要操作有增删改查。

本篇主要介绍Hibernate多对多关联:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 配置数据库连接字符串 -->
        <property name="connection.url"><![CDATA[jdbc:mysql://localhost:3306/test111?useUnicode=true&characterEncoding=utf8]]></property>
        <!-- 配置数据库连接用户名 -->
        <property name="connection.username">root</property>
        <!-- 配置数据库连接密码 -->
        <property name="connection.password">123456</property>
        <!-- 配置数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 配置数据库表生成策略 -->
        <!--<property name="hibernate.hbm2ddl.auto">update</property> -->
        <!-- 配置是否打印显示SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 配置是否格式化显示SQL语句 -->
        <property name="format_sql">true</property>
        <!-- 配置hibernate是否自动提交事务 -->
        <!--<property name="hibernate.connection.autocommit">true</property> -->

        <!--多对多关联 -->
        <mapping resource="com/great/entity6/User.hbm.xml"></mapping>
        <mapping resource="com/great/entity6/Role.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

User.hbm.xml

<?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 package="com.great.entity6">
    <class name="User" table="user1">
        <id name="id" column="id" type="int">
            <generator class="native">
            </generator>
        </id>

        <property name="name" column="name" type="string"></property>
        <set name="roles" table="mapping1">
            <key column="user_id"></key>
            <many-to-many class="com.great.entity6.Role" column="role_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Role.hbm.xml

<?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 package="com.great.entity6">
    <class name="Role" table="role1">
        <id name="id" column="id" type="int">
            <generator class="native">
            </generator>
        </id>

        <property name="roleName" column="roleName" type="string"></property>
        <set name="users" table="mapping1">
            <key column="role_id"></key>
            <many-to-many class="com.great.entity6.User" column="user_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

User.java

package com.great.entity6;

import java.util.Set;

public class User {
    private int id;
    private String name;
    private Set<Role> roles;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

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

}

Role.java

package com.great.entity6;

import java.util.Set;

public class Role {
    private int id;
    private String roleName;
    private Set<User> users;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

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

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

}

TestManyToMany.java

package com.great.test;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.great.entity6.Role;
import com.great.entity6.User;

public class TestManyToMany {
    static Session session;

    // 多表对多表关联
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        // 加载hibernate主配置文件
        Configuration cfg = new Configuration().configure();
        // 构建session工厂
        SessionFactory sf = cfg.buildSessionFactory();
        // 打开session
        session = sf.openSession();
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        // 关闭session,释放资源
        session.close();
    }

    // select1 ,通过User查询数据
    @Test
    public void testManyToManySelect1() {
        User user = (User) session.get(User.class, 1);
        System.out.println("用户姓名是:" + user.getName());
        System.out.println("用户的权限有:");
        Set<Role> roles = user.getRoles();
        Iterator<Role> it = roles.iterator();
        while (it.hasNext()) {
            System.out.print(it.next().getRoleName() + " ");
        }
    }

    // select2 ,通过Role查询数据
    @Test
    public void testManyToManySelect2() {
        Role role = (Role) session.get(Role.class, 1);
        System.out.println("权限名称为:" + role.getRoleName());
        System.out.println("拥有此权限的人有:");
        Set<User> users = role.getUsers();
        Iterator<User> it = users.iterator();
        while (it.hasNext()) {
            System.out.print(it.next().getName() + " ");
        }
    }

    /*
     * insert1,通过User插入数据 [发出七条语句,insert role1,insert role2,insert user,insert
     * mapping1 2条,role1表中保存2条数据,user1表中保存1条数据,mapping1表中保存2条数据]
     */
    @Test
    public void testManyToManySave1() {
        Transaction ts = session.beginTransaction();
        User user = new User();
        user.setName("王小胖");

        Role role1 = new Role();
        role1.setRoleName("删帖权限1");
        Role role2 = new Role();
        role2.setRoleName("管理员权限2");

        Set<Role> roles = new HashSet<Role>();
        Set<User> user1 = new HashSet<User>();
        Set<User> user2 = new HashSet<User>();
        roles.add(role1);
        roles.add(role2);
        user1.add(user);
        user2.add(user);

        user.setRoles(roles);// 和save2区别的地方

        session.save(role1);
        session.save(role2);
        session.save(user);
        ts.commit();
    }

    /*
     * insert2,通过Role插入数据 [发出七条语句,insert role1,insert role2,insert user,insert
     * mapping1 2条,role1表中保存2条数据,user1表中保存1条数据,mapping1表中保存2条数据]
     */
    @Test
    public void testManyToManySave2() {
        Transaction ts = session.beginTransaction();
        User user = new User();
        user.setName("王6胖");

        Role role1 = new Role();
        role1.setRoleName("删帖权限44");
        Role role2 = new Role();
        role2.setRoleName("管理员权限44");

        Set<Role> roles = new HashSet<Role>();
        Set<User> user1 = new HashSet<User>();
        Set<User> user2 = new HashSet<User>();
        roles.add(role1);
        roles.add(role2);
        user1.add(user);
        user2.add(user);

        role1.setUsers(user1);// 和save1区别的地方
        role2.setUsers(user2);

        session.save(role1);
        session.save(role2);

        ts.commit();
    }

    /*
     * delete1,通过User删除用户数据,通过发出一条select语句,两条delete语句,先delete mapping1,再delete
     * user1。
     */
    @Test
    public void testManyToManyDelete1() {
        Transaction ts = session.beginTransaction();
        User user = (User) session.get(User.class, 8);
        session.delete(user);
        ts.commit();
    }

    /*
     * delete2,通过Role删除权限数据,通过发出一条select语句,两条delete语句,先delete mapping1,再delete
     * role1。
     */
    @Test
    public void testManyToManyDelete2() {
        Transaction ts = session.beginTransaction();
        Role role = (Role) session.get(Role.class, 5);
        session.delete(role);
        ts.commit();
    }

    /* update1,通过User更新用户数据,添加权限, update user1,insert mapping1 */
    @Test
    public void testManyToManyUpdate1() {
        Transaction ts = session.beginTransaction();
        User user = (User) session.get(User.class, 4);
        user.setName("张二");
        // 获得权限
        Role role = (Role) session.get(Role.class, 1);
        Set<Role> roles = user.getRoles();
        roles.add(role);
        user.setRoles(roles);
        session.save(user);
        ts.commit();
    }

    /* update2,通过Role更新权限,添加此权限的拥有者, update role1,insert mapping1 */
    @Test
    public void testManyToManyUpdate2() {
        Transaction ts = session.beginTransaction();
        User user = (User) session.get(User.class, 4);
        // 获得权限
        Role role = (Role) session.get(Role.class, 2);
        role.setRoleName("系统权限");
        Set<User> users = role.getUsers();
        users.add(user);
        role.setUsers(users);
        session.save(role);
        ts.commit();
    }
}

数据库:

user1表

两个字段:id name

mapping1表

三个字段:id user_id role_id

role1表

两个字段: id roleName

注意:在mapping表上建立两个外键关系,user_id和role_id。

上一篇:【转】分布式一致性算法:Raft 算法(Raft 论文翻译)


下一篇:HttpGet和HttpPost的区别