10.Mybatis多对多的查询

1.结构图

1.User实体类

package com.itheima.pojo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String sex;
    private String address;
    private Date birthday;
    //多对多的关系映射:一个用户可以赋予多个角色
    private List<Role> role;

    public List<Role> getRole() {
        return role;
    }

    public void setRole(List<Role> role) {
        this.role = role;
    }


    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

2.Role实体类

package com.itheima.pojo;

import java.io.Serializable;
import java.util.List;

public class Role implements Serializable {
    //驼峰命名
    private Integer roleId;
    private String roleName;
    private String roleDesc;
    //多对多的关系映射:一个角色可以赋予多个用户
    private List<User> user;

    public List<User> getUser() {
        return user;
    }
    public void setUser(List<User> user) {
        this.user = user;
    }

    public Integer getRoleId() {
        return roleId;
    }

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

    public String getRoleName() {
        return roleName;
    }

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

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }
}

3.IUserDao用户接口

package com.itheima.dao;

import com.itheima.pojo.User;

import java.util.List;

public interface IUserDao {
    //查询所有
    List<User> findAll();
    //查询所有用户下的角色
    List<User> findAllUserAndRole();
}

4.IRoleDao用户接口

package com.itheima.dao;

import com.itheima.pojo.Role;

import java.util.List;

public interface IRoleDao {
    //查询所有角色
    List<Role> findAll();
    //查询所有用户加角色
    List<Role> findAllRole();
}

5.IUserMapper用户接口映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.IUserDao">

    <resultMap id="roleMap" type="com.itheima.pojo.User">
        <!--window系统数据库在此配置不区分大小写-->
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <result property="birthday" column="birthday"></result>
        <collection property="role" ofType="com.itheima.pojo.Role">
            <id property="roleId" column="id"></id>
            <result property="roleName" column="role_name"></result>
            <result property="roleDesc" column="role_desc"></result>
        </collection>
    </resultMap>

    <select id="findAll" resultMap="roleMap">
        select * from user
    </select>
    <select id="findAllUserAndRole" resultMap="roleMap">
        select u.*,r.id as rid,r.role_name,r.role_desc from user u
         left outer join user_role ur  on u.id = ur.uid
         left outer join role r on r.id = ur.rid
    </select>
</mapper>

6.IRoleMapper角色接口映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.IRoleDao">

    <resultMap id="userMap" type="com.itheima.pojo.Role">
        <!--window系统数据库在此配置不区分大小写-->
        <id property="roleId" column="id"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>

        <collection property="user" ofType="com.itheima.pojo.User">
            <id property="id" column="id"></id>
            <result property="username" column="username"></result>
            <result property="sex" column="sex"></result>
            <result property="address" column="address"></result>
            <result property="birthday" column="birthday"></result>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="userMap">
        select * from role
    </select>
    <!--左连接里的左连接:左连接套娃-->
    <select id="findAllRole" resultMap="userMap">
       select u.*,r.id as rid,r.role_name,r.role_desc from role r
        left outer join user_role ur  on r.id = ur.rid
        left outer join user u on u.id = ur.uid
    </select>
</mapper>
<!--总结一下:此时实体类的属性名和数据库字段名是不匹配的,
             所以需要配置别名通过resultMap来配置,
             这样数据库和实体类就能对应的上,然后后面的数据也可以直接采用resultMap这的方式配置

             但是如果当数据库名和字段名匹配的时候,就可以直接使用权限定类名(resultType的方式:"com.....dao中实体类")
             当然你也可以自己配
             -->

7.主配置文件SqlMapConfig.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--配置外部数据库-->
    <properties resource="jdbc.properties"></properties>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 配置Mapper映射文件地址 -->
    <mappers>
        <mapper resource="com/itheima/dao/IUserMapper.xml"></mapper>
        <mapper resource="com/itheima/dao/IRoleMapper.xml"></mapper>
        <!--还要一个一个配 不如package::为什么用不了待解决???-->
        <!--<package name="com.itheima.dao"/>-->
    </mappers>
</configuration>

8.外部数据源(数据库)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis(数据库名)?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456

9.测试类

package com.itheima;

import com.itheima.dao.IRoleDao;
import com.itheima.dao.IUserDao;
import com.itheima.pojo.Role;
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 com.itheima.pojo.User;

import java.io.InputStream;
import java.util.List;

public class ManyTest {
    //为了不用重复使用
    private InputStream inputStream;
    private SqlSessionFactory factory;
    private SqlSession sqlSession;
    private IUserDao userDao;
    private IRoleDao roleDao;
    /*初始化,在程序一运行的时候就准备好*/
    @Before
    public void  init() throws Exception{
        //1.获取配置文件SqlMapConfig的字节流
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory,让builder创建factory
        factory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.使用工厂创建session对象
        sqlSession = factory.openSession();
        //4.获取dao代理
        userDao = sqlSession.getMapper(IUserDao.class);
        //4.获取dao代理
        roleDao = sqlSession.getMapper(IRoleDao.class);
    }
    //查询所有用户:一对多的操作(使用UserMap)
    @Test
    public void findAllUser(){
        //5.使用userDao调用执行该方法--返回一个结果集
        List<User> users = userDao.findAll();
        for (User user:users){
            System.out.println("--------查询每一个用户的信息------------");
            System.out.println(user);
        }
    }
    //查询所有:一对多的操作(使用UserMap)
    @Test
    public void findAllRole(){
        //5.使用userDao调用执行该方法--返回一个结果集
        List<Role> roles = roleDao.findAll();
        for (Role role:roles){
            System.out.println("--------查询每一角色的信息------------");
            System.out.println(role);
        }
        /*没有toString方法会查询到地址*/
    }

    //多对多
    @Test
    public void findAllRoleUser(){
        //5.使用userDao调用执行该方法--返回一个结果集
        List<Role> roles = roleDao.findAllRole();
        for (Role role:roles){
            System.out.println("--------查询每一角色的信息------------");
            System.out.println(role);
            System.out.println(role.getUser());
        }
        /*没有toString方法会查询到地址*/
    }
    //多对多
    @Test
    public void findAllUserRole(){
        //5.使用userDao调用执行该方法--返回一个结果集
        List<User> users = userDao.findAllUserAndRole();
        for (User user:users){
            System.out.println("--------查询每一用户的信息角色------------");
            System.out.println(user);
            System.out.println(user.getRole());
        }
        /*没有toString方法会查询到地址*/
    }

    /*释放资源*/
    @After
    public void destroy() throws Exception{
        //7.事务提交
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        inputStream.close();
    }
}

10.依赖

<dependencies>
        <!--sql驱动:连接数据库用-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--测试的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--mybatis环境-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
    </dependencies>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值