码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis_03_多对多

时间:2019-07-03 00:49:56      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:用户信息   ima   date   connect   数据源   pre   window   apach   birt   

 

一、建表

1.role表

技术图片

2.user表

技术图片

3.user_role表  中间表

技术图片

 

 二、建立maven项目

1.目录结构

技术图片

 

 2.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cmdzz</groupId>
    <artifactId>mybatis03_ManyToMany</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <!--mysql连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>


    </dependencies>

</project>

 

3.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">

<!-- mybatis的主配置文件 -->
<configuration>

    <!--引入配置文件-->
    <properties resource="jdbcConfig.properties"></properties>

    <!--配置别名 映射文件里可以直接用domain里的类名 不区分大小写-->
    <typeAliases>
        <package name="com.cmdzz.domain"></package>
    </typeAliases>

    <!--配置环境
        default="mysql" 随便写 当时下面的 environment id 要一致
    -->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <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>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
  <!--  <mappers>
        <mapper resource="com/cmdzz/dao/IUserDao.xml"/>
    </mappers>
-->

    <!--直接扫描包-->
    <mappers>
        <package name="com.cmdzz.dao"></package>
    </mappers>
    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件
       如果是用注解来配置的话,此处应该使用class属性指定被注解的dao全限定类名
   -->
  <!--  <mappers>
        <mapper class="com.cmdzz.dao.IUserDao"/>
    </mappers>-->
</configuration>

 

4.IRoleDao.xml

<?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.cmdzz.dao.IRoleDao">

    <!--定义role表的ResultMap
        注意:mysql在windows下不区分大小写,在liunx下区分
    -->
    <resultMap id="roleMap" type="role">
        <id property="roleId" column="rid"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        
        <collection property="users" ofType="user">
            <id column="id" property="id"></id>
            <result column="username" property="userName"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
    </resultMap>

    <!--查询所有-->
  <!--  <select id="findAll" resultMap="roleMap">
        select * from role;
    </select>-->

    <select id="findAll" resultMap="roleMap">
      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>

 

5.IUserDao.xml

<?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.cmdzz.dao.IUserDao">

    <!--定义User的resultMap-->
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="userName" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>

        <!--配置角色集合的映射-->
        <collection property="roles" ofType="role">
            <id property="roleId" column="rid"></id>
            <result property="roleName" column="role_name"></result>
            <result property="roleDesc" column="role_desc"></result>

        </collection>

    </resultMap>

    <!--配置查询所有
      id="findAll" 是UserDao方法名 要一致
  -->
   <!-- <select id="findAll" resultType="user">
        select * from user
    </select>-->

    <select id="findAll" resultMap="userAccountMap">
       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>



    <!-- 根据id查询用户 -->
    <select id="findById" parameterType="INT" resultType="user">
        select * from user where id = #{uid}
    </select>


</mapper>

 

6.Role.java

package com.cmdzz.domain;

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

/**
 * @author cmdzz
 * @date 2019/7/2 - 16:01
 */
public class Role implements Serializable {
    private Integer roleId;
    private String roleName;
    private String roleDesc;

    //多对多的关系映射 一个角色可以赋予多个用户
    private List<User> users;

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

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

    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 + ‘\‘‘ +
                ‘}‘;
    }
}

 

7.User.java

package com.cmdzz.domain;

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

/**
 * @author cmdzz
 * @date 2019/6/26 - 12:01
 */
public class User implements Serializable {

    /**
     * 属性要和表的列名一样
     */
    private Integer id;
    private String userName;
    private Date birthday;
    private String sex;
    private String address;

    //多对多的关系映射,一个用户可以具备多个角色
    private List<Role> roles;

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

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

    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 Date getBirthday() {
        return birthday;
    }

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

    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;
    }


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

 

8.IRoleDao.java

package com.cmdzz.dao;

import com.cmdzz.domain.Role;

import java.util.List;

/**
 * @author cmdzz
 * @date 2019/7/2 - 16:02
 */
public interface IRoleDao {

    /**
     * 查询所有角色
     * @return
     */
    List<Role> findAll();
}

 

9.IUserDao.java

package com.cmdzz.dao;

/**
 * @author cmdzz
 * @date 2019/6/26 - 12:07
 */

import com.cmdzz.domain.User;

import java.util.List;

/**
 * 用户的持久层接口
 */
public interface IUserDao {

    /**
     * 查询所有操作
     * @return
     */
   /*注解的方式 @Select("select * from user")*/
    List<User> findAll();



    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    User findById(Integer userId);


}

 

10.jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xxxdb
jdbc.username=root
jdbc.password=******

 

 

 

11.RoleTest.java

package com.cmdzz.test;

/**
 * @author cmdzz
 * @date 2019/7/2 - 16:09
 */


import com.cmdzz.dao.IRoleDao;
import com.cmdzz.domain.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 java.io.InputStream;
import java.util.List;

/**
 * @author cmdzz
 * @date 2019/6/26 - 17:21
 */
public class RoleTest {


    private InputStream in;
    private SqlSession sqlSession;
    private IRoleDao roleDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        roleDao = sqlSession.getMapper(IRoleDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {

        //5.执行查询所有方法
        List<Role> roles = roleDao.findAll();
        for(Role role:roles){
            System.out.println("角色" +
                    "" +
                    "信息====================");
            System.out.println(role);
            System.out.println(role.getUsers());

        }

    }




}

 

12.UserTest.java

package com.cmdzz.test;

import com.cmdzz.dao.IUserDao;
import com.cmdzz.domain.User;
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.InputStream;
import java.util.List;

/**
 * @author cmdzz
 * @date 2019/6/26 - 17:21
 */
public class UserTest {


    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession();
        //4.获取dao的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
    * 测试查询所有
    */
    @Test
    public void testFindAll() {

        //5.执行查询所有方法
        List<User> users = userDao.findAll();
        for(User user:users){
            System.out.println("用户信息====================");
            System.out.println(user);
            System.out.println(user.getRoles());
        }

    }




}

 

13.Role测试

数据库语句执行结果

技术图片

 

RoleTest.java  findAll()测试结果

技术图片

 

 

14.Use测试

数据库语句执行结果

 

 技术图片

UserTest.java findAll()执行

技术图片

 

Mybatis_03_多对多

标签:用户信息   ima   date   connect   数据源   pre   window   apach   birt   

原文地址:https://www.cnblogs.com/cmdzhizhu/p/11123765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!