Mybatis映射及ResultMap示例

本文详细介绍了Mybatis映射文件XxxMapper.xml的使用,包括namespace、id、parameterType和resultType的概念及用法。通过具体示例展示了如何创建数据库、工程、配置文件,并创建实体类、接口、映射文件和测试类。同时,文章讨论了parameterType的基础数据类型和复杂数据类型的使用,以及多参数查询的两种实现方式。此外,重点解析了resultMap的使用,包括其与resultType的区别和在复杂映射情况下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1.映射文件XxxMapper.xml

1.1语法

<?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="namespace="cn.kgc.mapper.UserMapper"">
	<select id="findCount" …
		……
	</select>
</mapper>

1.2namespace:命名空间

namespace的命名必须跟某个接口同名。

1.3id:命名空间中唯一的标识符

接口中的方法名与映射文件中的SQL语句id一一对应

1.4parameterType:参数类型

传入SQL语句的参数类型(接口的形参)

1.5resultType:返回值

SQL语句返回值类型的完整类名或别名,也就是接口中的方法返回值。

1.6示例

需求:根据用户名对用户表进行模糊查询。

(1)创建数据库

(2)创建工程、目录

在这里插入图片描述

(3)pom.xml配置依赖

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.36</version>
</dependency>

(4)创建实体类

package cn.kgc.entity;

public class User {
    private Integer id;
    private String userCode;
    private String userName;
    private String userPassword;
    private Integer gender;
    private String birthday;
    private String phone;
    private String address;
    private Integer userRole;
    private Integer createdBy;
    private String creationDate;
    private Integer modifyBy;
    private String modifyDate;

    private String userRoleName;


    public User() {
    }

    public User(String userCode, Integer userRole) {
        this.userCode = userCode;
        this.userRole = userRole;
    }

    public User(String userCode, String userName, String userPassword, Integer gender, String birthday, String phone, String address, Integer userRole, Integer createBy, String creationDate, Integer modifyBy, String modifyDate) {
        this.userCode = userCode;
        this.userName = userName;
        this.userPassword = userPassword;
        this.gender = gender;
        this.birthday = birthday;
        this.phone = phone;
        this.address = address;
        this.userRole = userRole;
        this.createdBy = createBy;
        this.creationDate = creationDate;
        this.modifyBy = modifyBy;
        this.modifyDate = modifyDate;
    }

    public User(Integer id, String userCode, String userName, String userPassword, Integer gender, String birthday, String phone, String address, Integer userRole, Integer createBy, String creationDate, Integer modifyBy, String modifyDate) {
        this.id = id;
        this.userCode = userCode;
        this.userName = userName;
        this.userPassword = userPassword;
        this.gender = gender;
        this.birthday = birthday;
        this.phone = phone;
        this.address = address;
        this.userRole = userRole;
        this.createdBy = createBy;
        this.creationDate = creationDate;
        this.modifyBy = modifyBy;
        this.modifyDate = modifyDate;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }

    public String getUserRoleName() {
        return userRoleName;
    }

    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getBirthday() {
        return birthday;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

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

    public Integer getUserRole() {
        return userRole;
    }

    public void setUserRole(Integer userRole) {
        this.userRole = userRole;
    }

    public Integer getCreateBy() {
        return createdBy;
    }

    public void setCreateBy(Integer createBy) {
        this.createdBy = createBy;
    }

    public String getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(String creationDate) {
        this.creationDate = creationDate;
    }

    public Integer getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }

    public String getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(String modifyDate) {
        this.modifyDate = modifyDate;
    }
}

(5)配置主配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
        "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"></properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="cn/kgc/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

(6)jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms
username=root
password=123

(7)接口UserMapper.java

package cn.kgc.mapper;

import cn.kgc.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    //查询记录数
    public Integer findCount();
    //添加数据
    public Integer addUser(User user);
    //删除数据
    public Integer deleteUser(Integer id);
    //通过用户名和角色id查询
    public List<User> findByUser(@Param("userName") String userName, @Param("userRole") Integer userRole);
    //通过模糊用户名称和角色id查询
    public List<User> findByUser1(User user);
    //通过用户mine和用户角色Map容器参数查询列表
    public List<User> findByMap(Map<String,Object> map);

    //resultMap实战
    public List<User> findByResultMap(User user);
}

(8)工具类MyBatisUtil

package cn.kgc.util;

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory = null;

    static {
        String config = "mybatis-config.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    获取SqlSession
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if(factory != null){
            sqlSession = factory.openSession();
        }
        return sqlSession;
    }
}

(9)测试类TestUserMapper.java

package cn.kgc.test;

import cn.kgc.entity.User;
import cn.kgc.mapper.UserMapper;
import cn.kgc.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;

public class testUser {
    @Test
    public void testFindCount(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        Integer count = sqlSession.getMapper(UserMapper.class).findCount();
        System.out.println("记录数:"+count);
    }

    @Test
    public void testAdd(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        User user = new User();
        user.setUserCode("zhangsan");
        user.setUserName("张三");
        user.setUserPassword("111111");
        user.setGender(1);
        user.setBirthday("1998-08-08");
        user.setPhone("13333333333");
        user.setAddress("南京市");
        user.setUserRole(1);
        user.setCreateBy(1);
        user.setCreationDate("2020-09-09 18:13:23");
        user.setModifyBy(null);
        user.setModifyDate(null);
        sqlSession.getMapper(UserMapper.class).addUser(user);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testDelete(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        sqlSession.getMapper(UserMapper.class).deleteUser(16);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testByUser(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        List<User> list = sqlSession.getMapper(UserMapper.class).findByUser("王", 3);
        for(User user:list){
            System.out.println("用户名:"+user.getUserCode()+"  名称:"+user.getUserName()+"  密码:"+user.getUserPassword());
        }
        System.out.println(list);
        sqlSession.close();
    }

    @Test
    public void testFindByUser1(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        User user = new User();
        user.setUserName("王");
        user.setUserRole(3);
        List<User> list = sqlSession.getMapper(UserMapper.class).findByUser1(user);
        for (User u:list){
            System.out.println("用户名称:"+u.getUserName()+"  用户密码:"+u.getUserPassword());
        }
        sqlSession.close();
    }

    @Test
    public void testFindByMap(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        HashMap<String , Object> map = new HashMap<>();
        map.put("userName","王");
        map.put("userRole",3);
        List<User> list = sqlSession.getMapper(UserMapper.class).findByMap(map);
        for (User u:list){
            System.out.println("用户名称:"+u.getUserName()+"  用户密码:"+u.getUserPassword());
        }
        sqlSession.close();
    }

    @Test
    public void testFindByResultMap(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        User user = new User();
        user.setUserName("王");
        user.setUserRole(3);
        List<User> list = sqlSession.getMapper(UserMapper.class).findByResultMap(user);
        for (User u:list){
            System.out.println("用户名:"+u.getUserCode()+"  用户名称:"+u.getUserName()+"  角色名:"+u.getUserRoleName());
        }
        sqlSession.close();
    }
}

1.7parameterType基础数据类型/复杂数据类型

(1)基础数据类型

int、String、Date等
只能传入一个,通过#{参数名}即可获取传入的值

(2)复杂数据类型

Java实体类、Map等
通过#{属性名}或者#{map的keyName}即可获取传入值

1.8多参实现

需求:通过用户名模糊匹配和用户角色id进行条件查询
在这里插入图片描述

(1)第一种实现

接口UserMapper.java
public List<User> findByUser(User user);
映射文件UserMapper.xml
<select id="findByUser" resultType="cn.kgc.entity.User" parameterType="cn.kgc.entity.User">
    select * from smbms_user where userName like concat('%',#{userName},'%') and userRole = #{userRole}
</select>
测试文件TestUserMapper
@Test
public void testFindByUser(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    User user = new User();
    user.setUserName("王");
    user.setUserRole(3);
    List<User> list = sqlSession.getMapper(UserMapper.class).findByUser(user);
    for (User u:list){
        System.out.println("用户名称:"+u.getUserName()+"  用户密码:"+u.getUserPassword());
    }
    sqlSession.close();
}

(2)第二种实现

接口UserMapper.java
public List<User> findByMap(Map<String,Object> map);
映射文件UserMapper.xml
<select id="findByMap"  resultType="cn.kgc.entity.User" parameterType="java.util.Map">
    select * from smbms_user where userName like concat('%',#{userName},'%') and userRole = #{userRole}
</select>
TestUserMapper
@Test
public void testFindByMap(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    HashMap<String , Object> map = new HashMap<>();
    map.put("userName","王");
    map.put("userRole",3);
    List<User> list = sqlSession.getMapper(UserMapper.class).findByMap(map);
    for (User u:list){
        System.out.println("用户名称:"+u.getUserName()+"  用户密码:"+u.getUserPassword());
    }
    sqlSession.close();
}

1.9resultMap 描述如何将结果集映射到Java对象

resultType:直接表示返回类型

基本数据类型
复杂数据类型

resultMap:对外部resultMap的引用

应用场景:
数据库字段信息与对象属性不一致
复杂的联合查询,自由控制映射结果
二者不能同时存在,本质上都是Map数据结构

1.10通过用户名和角色编码查询用户列表

(1)实体类User.java

private String userRoleName;
public String getUserRoleName() {
    return userRoleName;
}

public void setUserRoleName(String userRoleName) {
    this.userRoleName = userRoleName;
}

(2)接口UserMapper.java

public List<User> findByResultMap(User user);

(3)映射文件UserMapper.xml

<select id="findByResultMap"  resultMap="userList" parameterType="cn.kgc.entity.User">
    select a.userCode,a.userName,b.roleName
    from smbms_user as a left join smbms_role as b on a.userRole = b.id
    where userName like concat('%',#{userName},'%')
    and userRole = #{userRole}
</select>
<resultMap id="userList" type="cn.kgc.entity.User">
    <result property="userCode" column="userCode"></result>
    <result property="userName" column="userName"></result>
    <result property="userRoleName" column="roleName"></result>
</resultMap>

(4)测试类TestUserMapper.java

@Test
public void testFindByResultMap(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    User user = new User();
    user.setUserName("王");
    user.setUserRole(3);
    List<User> list = sqlSession.getMapper(UserMapper.class).findByResultMap(user);
    for (User u:list){
        System.out.println("用户名:"+u.getUserCode()+"  用户名称:"+u.getUserName()+"  角色名:"+u.getUserRoleName());
    }
    sqlSession.close();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值