Mybatis学习笔记之---多表查询(2)

Mybatis多表查询(2)

(一)举例

用户和角色

一个用户可以有多个角色,一个角色可以赋予多个用户

(二)步骤

  1、建立两张表:用户表,角色表,让用户表和角色表具有多对多的关系。需要使用中间表,中间表中包含各自的主键,在中间表中是外键。

   2、建立两个实体类:用户实体类和角色实体类,让用户和角色的实体类能体现出来多对多的关系各自包含对方一个集合引用

   3、建立两个配置文件用户的配置文件角色的配置文件

   4、实现配置:当我们查询用户时,可以同时得到用户所包含的角色信息当我们查询角色时,可以同时得到角色的所赋子的用户信息

(三)代码实现

 Mybatis学习笔记之---多表查询(2)_第1张图片

1.pom.xml

<dependencies>
  <dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.11version>
  dependency>
  <dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.41version>
  dependency>
  <dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.4.6version>
  dependency>

dependencies>

 

2.Role.java

package entity;



import java.util.List;



public class Role {

    private int rid;

    private String rolename;

    //多对多的关系映射,一个角色可以赋予多个用户

    private List users;



    public int getRid() {

        return rid;

    }



    public void setRid(int rid) {

        this.rid = rid;

    }



    public String getRolename() {

        return rolename;

    }



    public void setRolename(String rolename) {

        this.rolename = rolename;

    }



    public List getUsers() {

        return users;

    }



    public void setUsers(List users) {

        this.users = users;

    }



    @Override

    public String toString() {

        return "Role{" +

                "rid=" + rid +

                ", rolename='" + rolename + '\'' +

                ", users=" + users +

                '}';

    }

}

 

3.Users.java

package entity;



import java.util.List;



public class Users {

    private int uid;

    private String username;

    private String password;

    //多对多的关系映射,一个用户可以赋予多个角色

    private List roles;



    public int getUid() {

        return uid;

    }



    public void setUid(int uid) {

        this.uid = uid;

    }



    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 List getRoles() {

        return roles;

    }



    public void setRoles(List roles) {

        this.roles = roles;

    }



    @Override

    public String toString() {

        return "Users{" +

                "uid=" + uid +

                ", username='" + username + '\'' +

                ", password='" + password + '\'' +

                ", roles=" + roles +

                '}';

    }

}

 

4.SqlMapperConfig.xml

xml version="1.0" encoding="UTF-8" ?>

DOCTYPEconfiguration

        PUBLIC"-//mybatis.org//DTD Config 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-config.dtd">



<configuration>

    

    <environments default="mysql">

        

        <environment id="mysql">

            

            <transactionManager type="JDBC">transactionManager>

            

            <dataSource type="POOLED">

                

                <property name="driver" value="com.mysql.jdbc.Driver">property>

                <property name="url" value="jdbc:mysql://localhost:3306/zml01?useUnicode=true&characterEncoding=utf-8">property>

                <property name="username" value="root">property>

                <property name="password" value="root">property>

            dataSource>

            

        environment>

    environments>

    

<mappers>

    <mapper resource="dao/UserDao.xml">mapper>

    <mapper resource="dao/RoleDao.xml">mapper>



mappers>

configuration>

 

5.UserDao.java

package dao;



        import entity.Users;



        import java.util.List;



public interface UserDao {

     List findAll();

     Users find(int id);

}

 

6.UserDao.xml

xml version="1.0" encoding="UTF-8" ?>

DOCTYPEmapper

        PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.UserDao">

    <resultMap id="urMap" type="entity.Users">

        <id property="uid" column="uid">id>

        <result property="username" column="username">result>

        <result property="password" column="password">result>

        <collection property="roles" ofType="entity.Role">

            <id property="rid" column="rid">id>

            <result property="rolename" column="rolename">result>

        collection>

    resultMap>

    

    <select id="findAll" resultMap="urMap">

        select * from users u LEFT OUTER JOIN users_role ur on u.uid=ur.uid LEFT OUTER JOIN role r on r.rid=ur.rid

    select>

    

    <select id="find" resultType="entity.Users">

        select * from users where id=#{id}

    select>



mapper>

 

7.UserTest.java

package test;



import dao.UserDao;

import entity.Users;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;



import java.io.IOException;

import java.io.InputStream;

import java.util.List;



public class UserTest {

    private InputStream in;

    private SqlSession sqlSession;

    private UserDao UserDaoImpl;

    @Before

    public void init() throws IOException {

        //1.读取配置文件

        in= Resources.getResourceAsStream("SqlMapperConfig.xml");

        //2.创建SqlSessionFactory工厂

        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();

        SqlSessionFactory factory=builder.build(in);

        //3.使用工厂生产SqlSession对象

        sqlSession=factory.openSession();

        //4.使用SqlSession创建dao接口的代理对象

        UserDaoImpl=sqlSession.getMapper(UserDao.class);

    }

    @After

    public void destroy() throws IOException {

        //提交事务

        sqlSession.commit();

        //6.释放资源

        sqlSession.close();

        in.close();

    }



    /**

     * 查询所有

     * @throws IOException

     */

    @Test

    public void findall() throws IOException {



        //5.使用代理对象执行方法

        List users=UserDaoImpl.findAll();

        for(Users u:users){

            System.out.println(u);

        }



    }

}

 

8.RoleDao.java

package dao;



import entity.Role;



import java.util.List;



public interface RoleDao {

    List findAll();

}

 

9.RoleDao.xml

xml version="1.0" encoding="UTF-8" ?>

DOCTYPEmapper

        PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.RoleDao">

    <resultMap id="ruMap" type="entity.Role">

        <id property="rid" column="rid">id>

        <result property="rolename" column="rolename">result>

        <collection property="users" ofType="entity.Users">

            <id property="uid" column="uid">id>

            <result property="username" column="username">result>

            <result property="password" column="password">result>

        collection>

    resultMap>

    

    <select id="findAll" resultMap="ruMap">

        select * from role r LEFT OUTER JOIN users_role ur on r.rid=ur.rid LEFT OUTER JOIN users u on u.uid=ur.uid

    select>





mapper>

 

10.RoleTest.java

package test;

import dao.RoleDao;

import dao.UserDao;

import entity.Role;

import entity.Users;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;



import java.io.IOException;

import java.io.InputStream;

import java.util.List;

public class RoleTest {

    private InputStream in;

    private SqlSession sqlSession;

    private RoleDao roleDaoImpl;

    @Before

    public void init() throws IOException {

        //1.读取配置文件

        in= Resources.getResourceAsStream("SqlMapperConfig.xml");

        //2.创建SqlSessionFactory工厂

        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();

        SqlSessionFactory factory=builder.build(in);

        //3.使用工厂生产SqlSession对象

        sqlSession=factory.openSession();

        //4.使用SqlSession创建dao接口的代理对象

        roleDaoImpl=sqlSession.getMapper(RoleDao.class);

    }

    @After

    public void destroy() throws IOException {

        //提交事务

        sqlSession.commit();

        //6.释放资源

        sqlSession.close();

        in.close();

    }



    /**

     * 查询所有

     * @throws IOException

     */

    @Test

    public void findall() throws IOException {

        //5.使用代理对象执行方法

        List roles=roleDaoImpl.findAll();

        for(Role r:roles){

            System.out.println(r);

        }

    }

}

 

你可能感兴趣的:(Mybatis学习笔记之---多表查询(2))