MyBatis学习笔记(六)一对多的关联查询和传递多个参数

首发于我的博客 和尚的博客
本文讲解一对多的关联查询,传递多个参数。


源码获取github

1.传递多个参数


  1. 当你的形参传递>1个的时候,parameterType不写,让其自动处理
  2. #{值},默认为arg0,arg1…..或param1,param2,,,
  3. 若在接口中注解了@Param(相当于指明了key值),即也可以写xxx,默认的也可以写,相当于3个值

2.结构

3.数据库属性文件

同之前

4.核心配置文件

mybatis-config.xml



<configuration>
    
    <properties resource="jdbc.properties"/>
    
    <typeAliases>
        
        
        
        <package name="com.hs.model"/>
    typeAliases>
    
    <environments default="development">
        <environment id="development">
            
            
            <transactionManager type="JDBC" />
            
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.mysql.driver}" />  
                <property name="url" value="${jdbc.mysql.url}" />  
                <property name="username" value="${jdbc.mysql.username}" /> 
                <property name="password" value="${jdbc.mysql.password}" /> 
            dataSource>
        environment>
    environments>

    
    <mappers>
         
        <mapper resource="com/hs/model/UserMapper.xml"/>
        <mapper resource="com/hs/model/RoleMapper.xml"/>
        
        
    mappers>
configuration>

5.持久化类

Role.java

package com.hs.model;

import java.util.List;

public class Role {

    private Integer role_id;
    private String role_name;
    private String role_key;
    private Integer status;

    //关联对象,一对多,一个角色可以有多个用户
    private List userList;

    public List getUserList() {
        return userList;
    }

    public void setUserList(List userList) {
        this.userList = userList;
    }

    public Integer getRole_id() {
        return role_id;
    }

    public void setRole_id(Integer role_id) {
        this.role_id = role_id;
    }

    public String getRole_name() {
        return role_name;
    }

    public void setRole_name(String role_name) {
        this.role_name = role_name;
    }

    public String getRole_key() {
        return role_key;
    }

    public void setRole_key(String role_key) {
        this.role_key = role_key;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Role{" +
                "role_id=" + role_id +
                ", role_name='" + role_name + '\'' +
                ", role_key='" + role_key + '\'' +
                ", status=" + status +
                ", userList=" + userList +
                '}';
    }
}

User.java

package com.hs.model;

import java.util.Date;

public class User {

    private Integer user_id;
    private String account;
    private String password;
    private String user_name;
    private Integer status;
    private Date login_time;
    private String ip;
    private Integer fk_role_id;
    //关联对象 一对一或多对一
    private Role role;

    public Integer getUser_id() {
        return user_id;
    }

    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

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

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getLogin_time() {
        return login_time;
    }

    public void setLogin_time(Date login_time) {
        this.login_time = login_time;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getFk_role_id() {
        return fk_role_id;
    }

    public void setFk_role_id(Integer fk_role_id) {
        this.fk_role_id = fk_role_id;
    }

    public Role getRole() {
        return role;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "user_id=" + user_id +
                ", account='" + account + '\'' +
                ", password='" + password + '\'' +
                ", user_name='" + user_name + '\'' +
                ", status=" + status +
                ", login_time=" + login_time +
                ", ip='" + ip + '\'' +
                ", fk_role_id=" + fk_role_id +
                ", role=" + role +
                '}';
    }
}

6.XML映射文件

RoleMapper.xml




<mapper namespace="com.hs.dao.RoleDao">
    <resultMap type="Role" id="BaseResultMapper">
        <id column="role_id" property="role_id"/>
        <result column="role_name" property="role_name"/>
        <result column="role_key" property="role_key"/>
        <result column="status" property="status"/>
    resultMap>
    <sql id="sys_role_columns">
        role_id,role_name,role_key,status
    sql>
    <sql id="sys_role_columns_alias">
        ${alias}.role_id,${alias}.role_name,${alias}.role_key,${alias}.status
    sql>

    <resultMap id="SimpleResultMapper" type="Role" extends="BaseResultMapper">
        
        
        <collection property="userList"
                    javaType="java.util.List"
                    ofType="User"
                    column="role_id"
                    select="com.hs.dao.UserDao.getUserByFk"/>
    resultMap>
    <select id="getRoleByPk" parameterType="_int" resultMap="SimpleResultMapper">
        select
        <include refid="sys_role_columns"/>
        from sys_role
        where role_id = #{role_id}
    select>


    <resultMap id="JoinResultMapper" type="Role" extends="BaseResultMapper">
        
        <collection property="userList" javaType="list" ofType="com.hs.model.User"
                    resultMap="com.hs.dao.UserDao.BaseResultMapper"/>
        
    resultMap>
    <select id="getRoleByLeftJoin" parameterType="_int" resultMap="JoinResultMapper">
        SELECT
        <include refid="com.hs.dao.UserDao.sys_user_colums_alias">
            <property name="alias" value="su"/>
        include>
        ,
        <include refid="sys_role_columns_alias">
            <property name="alias" value="sr"/>
        include>
        FROM
        sys_role sr
        LEFT JOIN sys_user su ON sr.role_id = su.fk_role_id
        WHERE
        sr.role_id =#{role_id}
    select>
mapper>

UserMapper.xml




<mapper namespace="com.hs.dao.UserDao">
    
    <resultMap id="BaseResultMapper" type="User">
        <id column="user_id" property="user_id" />
        <result column="account" property="account" />
        <result column="passwrod" property="pasword" />
        <result column="user_name" property="user_name" />
        <result column="status" property="status" />
        <result column="login_time" property="login_time" />
        <result column="ip" property="ip" />
        <result column="fk_role_id" property="fk_role_id" />
    resultMap>
    <resultMap id="SimpleResultMapper" type="User" extends="BaseResultMapper"> 
        
        
        <association property="role" javaType="Role" column="fk_role_id" select="com.hs.dao.RoleDao.getRoleByPk"/>
    resultMap>
    <sql id="sys_user_colums">
        user_id,account,password,user_name,status,login_time,ip,fk_role_id
    sql>
    <sql id="sys_user_colums_alias">
        ${alias}.user_id,${alias}.account,${alias}.password,${alias}.user_name,${alias}.status,${alias}.login_time,${alias}.ip,${alias}.fk_role_id
    sql>

    <select id="getUserByFk" parameterType="_int" resultMap="BaseResultMapper">
        select <include refid="sys_user_colums"/>
        from sys_user
        where fk_role_id = #{role_id}
    select>

    
    <select id="getUser" resultMap="BaseResultMapper">
        select <include refid="sys_user_colums"/>
        from sys_user
        where account=#{account} and password=#{password}
    select>
mapper>

7.接口

RoleDao.java

package com.hs.dao;

import com.hs.model.Role;

public interface RoleDao {

    /**
     * select方式,先在role表查出主键,然后传给user表当做条件,查询出user的信息
     *
     * @param role_id
     * @return
     */
    Role getRoleByPk(int role_id);

    /**
     * 利用连接查询方式,查询结果集
     *
     * @param role_id
     * @return
     */
    Role getRoleByLeftJoin(int role_id);
}

UserDao.java

package com.hs.dao;

import com.hs.model.User;
import org.apache.ibatis.annotations.Param;

public interface UserDao {

    /**
     * 传递多个参数
     * 1.当你的形参传递>1个的时候,parameterType不写,让其自动处理
     * 2.#{值},默认为arg0,arg1.....或param1,param2,,,
     * 若在dao注解了@xxx(相当于指明了key值),即也可以写xxx,默认的也可以写,相当于3个值
     */
    User getUser(@Param("account") String account, @Param("password") String password);
}

8.日志配置文件

mybatis-config.xml

# 日志配置文件Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
# 如果要显示SQL语句,那么这个位置需要配置为命名空间log4j.logger.命名空间
log4j.logger.com.hs.dao.UserDao=TRACE
log4j.logger.com.hs.dao.RoleDao=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

9.测试类

MyBatisTest.java

package com.hs.test;

import com.hs.dao.RoleDao;
import com.hs.dao.UserDao;
import com.hs.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * 接口代理模式实现操作,在xxDao接口中,定义方法:  sql语句返回的结果类型 sql语句的id(要传的值);
 * 不用写实现类,直接写测试类,具体实现见测试类
 * sql的映射文件的命名空间跟接口的全路径一致
 * 可以根据接口的返回类型自动判断使用selectOne还是selectList eg:返回的是一个对象的为one,返回的是list的就是list,如果是List,也是list
 */
public class MyBatisTest {

    /**
     * 利用select方式,
     */
    @Test
    public void getUserByPk(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlsession();
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            System.out.println(roleDao.getRoleByPk(-100));
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

    /**
     * 利用连接方式查询
     */
    @Test
    public void getUserByFk(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlsession();
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            System.out.println(roleDao.getRoleByLeftJoin(-100));
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

    /**
     * 传递多个参数
     */
    @Test
    public void getUser(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlsession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            String account = "admin";
            String password = "admin";
            System.out.println(userDao.getUser(account,password));
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

}

你可能感兴趣的:(MyBatis学习总结)