Mybatis中resultMap标签和sql标签的设置方式

目录
  • resultMap标签和sql标签的设置
    • 1、项目目录
    • 2、数据库中的表的信息
    • 3、配置文件的信息
    • 4、User类
    • 5、IUserDao接口
    • 6、MybatisTest
    • 7、运行结果
  • resultMap标签的使用规则
    • 自定义结果映射规则
    • association联合查询
    • 使用association进行分布查询
    • collection分步查询

resultMap标签和sql标签的设置

1、项目目录

2、数据库中的表的信息

3、配置文件的信息

1、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>
    <!--配置环境-->
    <environments default="mysql">
<!--        配置mysql环境-->
        <environment id="mysql">
<!--            配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>
<!--            配置数据源(连接池)-->
            <dataSource type="POOLED">
<!--                配置数据库的基本信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="111111"/>
            </dataSource>
        </environment>
    </environments>
<!--    指定映射配置文件的位置,映射配置文件指的是每一个dao独立的配置文件-->
    <mappers>
        <mapper resource="com/mybatis/dao/IUserDao.xml"/>
    </mappers>
</configuration>

2、IUserDao.xml

其中的mapper标签中的namespace属性指的就是持久层中的接口,这里的sql语句都是对应这个接口中的方法,也就是指定了命名空间。

在这里resultMap标签是查询结果的列名和实体类的属性名的对应关系,也就是说我们类中的属性名不一定和数据库中的保持一致,其中property配置的就是类中的属性名,column设置的就是数据库中表的字段名。

在sql语句的标签中之前的,resultType变成了resultMap。sql标签中直接写的是就是sql语句,这个可以有效的避免重复的写sql相同代码,如果要引用sql标签中内容,在对应的语句中需要引用Include标签,具体的可以看下面的代码。

<?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.mybatis.dao.IUserDao">
<!--    配置,查询结果的列名和实体类的属性名的对应关系-->
    <resultMap id="userMap" type="com.mybatis.domain.User">
<!--        主键字段对应-->
        <id property="userId" column="id"></id>
<!--        非主键字段对应-->
        <result property="userName" column="username"></result>
        <result property="userAddress" column="address"></result>
        <result property="userSex" column="sex"></result>
        <result property="userBirthday" column="birthday"></result>
    </resultMap>
    <sql id="defaultUser">
        select * from users
    </sql>
<!--    查询所有-->
    <select id="findAll" resultMap="userMap">
        <include refid="defaultUser"></include>
    </select>
    <select id="findById" parameterType="INT" resultMap="userMap">
        select * from users where id = #{uid}
    </select>
</mapper>

4、User类

package com.mybatis.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
    private Integer userId;
    private String userName;
    private Date userBirthday;
    private String userSex;
    private String userAddress;
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Date getUserBirthday() {
        return userBirthday;
    }
    public void setUserBirthday(Date userBirthday) {
        this.userBirthday = userBirthday;
    }
    public String getUserSex() {
        return userSex;
    }
    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }
    public String getUserAddress() {
        return userAddress;
    }
    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }
    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userBirthday=" + userBirthday +
                ", userSex='" + userSex + '\'' +
                ", userAddress='" + userAddress + '\'' +
                '}';
    }
}

5、IUserDao接口

package com.mybatis.dao;
import com.mybatis.domain.User;
import java.util.List;
public interface IUserDao {
    /**
     * 查询所有用户
     * @return
     */
    List<User> findAll();
    /**
     * 根据ID查询用户信息
     * @param userId
     * @return
     */
    User findById(Integer userId);
}

6、MybatisTest

package com.mybatis.test;
import com.mybatis.dao.IUserDao;
import com.mybatis.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.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class MybatisTest {
    private InputStream  in;
    private SqlSession session;
    private IUserDao userDao;
    @Before
    public void init() throws Exception {
        this.in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        System.out.println(in);
        SqlSessionFactory factory = factoryBuilder.build(in);
//        this.session = factory.openSession(true);
        this.session = factory.openSession();
        this.userDao = session.getMapper(IUserDao.class);
    }
    @After
    public void destory() throws IOException {
        session.commit();
        this.in.close();
        this.session.close();
    }
    @Test
    public  void testFindAll() throws Exception{
        List<User> users = userDao.findAll();
        for (User user:users){
            System.out.println(user);
        }
    }
}

7、运行结果

resultMap标签的使用规则

自定义结果映射规则

<!-- resultMap自定义某个javabean的封装规则
       type:自定义规则的java类型
       id:唯一id方便引用
     -->
    <resultMap type="entity.Employee" id="getEmpByIdMap">
       <!-- id指定主键列的封装规则
           column:指定哪一列
           property:指定对应的javabean属性
        -->
       <id column="id" property="id"/>
       <!-- result定义普通列封装规则,若属性名与数据库对应表的列名相同可不写,
            mybatis会自动封装,但建议将所有的映射规则都写上
       -->
       <result column="name" property="name"/>
       <result column="sex" property="sex"/>
       <result column="email" property="email"/>
    </resultMap>
    <!-- public Employee getEmpById(Integer id) -->
    <select id="getEmpById" resultMap="getEmpByIdMap">
       select * from employee where id=#{id}
    </select>

association联合查询

association可以指定联合的javabean对象

  • property="dept":指定哪个属性是联合对象
  • javaType:指定这个属性的类型
<resultMap type="entity.Employee" id="getEmpAndDeptMap">
       <id column="id" property="id"/>
       <result column="empName" property="name"/>
       <result column="sex" property="sex"/>
       <result column="email" property="email"/>
       <!-- association可以指定联合的javabean对象
            property="dept":指定哪个属性是联合对象
            javaType:指定这个属性的类型-->
       <association property="dept" javaType="entity.Department">
           <id column="did" property="id"/>
           <result column="deptName" property="departmentName"/>
       </association>
    </resultMap>
    <!-- public Employee getEmpAndDept(Integer id) -->
    <select id="getEmpAndDept" resultMap="getEmpAndDeptMap">
       select e.id id,e.name empName,e.email email,e.sex sex,e.d_id d_id,
           d.id did,d.name deptName from employee e,dept d
           where e.d_id=d.id and e.id=#{id}
    </select>

使用association进行分布查询

1、先按照员工id查询员工信息将会调用查询员工的sql

2、根据查询员工信息中的d_id值去部门表中查出部门信息

3、部门设置到员工中

<resultMap type="entity.Employee" id="getEmpAndDeptStepMap">
       <id column="id" property="id"/>
       <result column="name" property="name"/>
       <result column="sex" property="sex"/>
       <result column="email" property="email"/>
       <!-- association定义关联对象的封装规则
            select:表明当前属性是调用select指定的方法查出的结果
            column:指定将那一列的值作为参数传给这个方法
             流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,
             并封装给property指定的属性
            -->
            <!-- discriminator鉴别器
                 column:指定判定的列名
                 javaType:列值对应的java类型
             -->
       <discriminator javaType="string" column="sex">
           <!-- resultType不能缺少 -->
           <case value="男" resultType="entity.Employee">
              <association property="dept" select="dao.DepartmentMapper.getDeptById"
                  column="d_id">
              </association>
           </case>
       </discriminator>
    </resultMap>
    <!-- public Employee getEmpByIdStep(Integer id) -->
    <select id="getEmpByIdStep" resultMap="getEmpAndDeptStepMap">
       select * from employee where id=#{id}
    </select>

嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则

<resultMap type="entity.Department" id="getDeptByIdPlusMap">
       <id column="did" property="id"/>
       <result column="deptName" property="departmentName"/>
       <!-- collection定义关联集合类型的属性的封装规则
            ofType:指定集合里面元素的类型             
        -->
       <collection property="emps" ofType="entity.Employee">
           <!-- 定义这个集合中元素的封装规则 -->
           <id column="eid" property="id"/>
           <result column="empName" property="name"/>
           <result column="sex" property="sex"/>
           <result column="email" property="email"/>
       </collection>
    </resultMap>
    <!-- public Department getDeptByIdPlus(Integer id) -->
    <select id="getDeptByIdPlus" resultMap="getDeptByIdPlusMap">
       select d.id did,d.name deptName,e.id eid,
           e.name empName,e.sex,e.email
           from dept d left join employee e
           on d.id=e.d_id
           where d.id=#{id}
    </select>

collection分步查询

<resultMap type="entity.Department" id="getDeptByIdStepMap">
       <id column="id" property="id"/>
       <result column="name" property="departmentName"/>
       <collection property="emps" select="dao.EmployeeMapperPlus.getEmpsByDeptId"
           column="{id}">
      <!-- 或则 column="{deptId=id}"-->
       </collection>
    </resultMap>
   <!-- public List<Employee> getEmpsByDeptId(Integer deptId -->
   <select id="getEmpsByDeptId" resultType="entity.Employee">
       select * from employee where d_id=#{deptId}
    </select>
    <!-- public Department getDeptByIdStep(Integer id) -->
    <select id="getDeptByIdStep" resultMap="getDeptByIdStepMap">
       select * from dept where id=#{id}
    </select>

当分布查询需要传递多个多个值时,将多个值封装map传递

colum=“{key1=column1,key2=colum2...}”

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Mybatis sqlMapConfig.xml中的mappers标签使用

    目录 sqlMapConfig.xml中的mappers标签 mappers(映射配置) 1.1:通过resource加载单个映射文件 1.2:通过mapper接口加载单个映射文件 1.3:批量加载mapper(推荐使用) sqlmapconfig核心标签说明以及配置 配置项详解 配置示例 sqlMapConfig.xml中的mappers标签 mappers(映射配置) 1.1:通过resource加载单个映射文件 < !– 加载映射文件 –> < mappers> < !

  • 使用Mybatis-Plus时的SqlSessionFactory问题及处理

    目录 使用Mybatis-Plus时的SqlSessionFactory问题 贴一下这两个类的源码,看一眼就明白了 还有MybatisSqlSessionFactoryBean的 springboot+mybatis-plus报错Property'sqlSessionFactory'or'sqlSessionTemplate'are required 使用Mybatis-Plus时的SqlSessionFactory问题 前些日子工作中出现一个问题,项目中使用了MybatisPlus,然后出现了

  • 关于MyBatis中SqlSessionFactory和SqlSession简解

    目录 [1]SqlSessionFactoryBuilder [2]SqlSessionFactory SqlSessionFactory 接口源码 SqlSessionFactory 有六个方法创建 SqlSession 实例 [3]非线程安全的SqlSession 永远不要在一个被管理域中引用SqlSession 语句执行方法 立即批量更新方法 事务控制方法 本地缓存 使用映射器 映射器注解 映射注解示例 mybatis官网中文文档:https://mybatis.org/mybatis-3

  • mysql+mybatis实现存储过程+事务 + 多并发流水号获取

    数据库存储过程 DROP PROCEDURE IF EXISTS `generate_serial_number_by_date`; CREATE PROCEDURE `generate_serial_number_by_date`( IN param_key varchar(100), IN param_org_id bigint, IN param_period_date_format varchar(20), OUT result bigint, OUT current_datestr v

  • 利用Java如何获取Mybatis动态生成的sql接口实现

    目录 前言 1.编写xml: SqlGenarate.mapper.xml 2.定义接口 3.实现接口 总结 前言 如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号.利用动态 SQL 这一特性可以彻底摆脱这种痛苦.通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态 SQL 语言来改进这种情形,这种语言可以被用在任意的 SQL 映射语句中. 目的:利

  • 聊聊mybatis sql的括号问题

    目录 mybatis sql的括号问题 mybatis多层括号(超过三层)解析不了 mybatis sql的括号问题 因为一段sql  要关联 A,B,C三个表,查三个表里的数据 一开始写的是 select * from a,b,c      结果出来很多重复数据 而三个表是用id关联的 所以改成 select * from a  where id in (select id from a,b,c 关联条件) 然后在mybatis里在写级联查询 把B,C表里的数据以数组的形式查出来 ok了  

  • Mybatis中resultMap标签和sql标签的设置方式

    目录 resultMap标签和sql标签的设置 1.项目目录 2.数据库中的表的信息 3.配置文件的信息 4.User类 5.IUserDao接口 6.MybatisTest 7.运行结果 resultMap标签的使用规则 自定义结果映射规则 association联合查询 使用association进行分布查询 collection分步查询 resultMap标签和sql标签的设置 1.项目目录 2.数据库中的表的信息 3.配置文件的信息 1.SqlMapConfig.xml文件 <?xml

  • mybatis中resultMap 标签的使用教程

    MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动.创建connection.创建statement.手动设置参数.结果集检索等jdbc繁杂的过程代码. MyBatis特点: 1.开源的优秀持久层框架 2.SQL语句与代码分离 3.面向配置的编程 4.良好支持复杂数据映射 5.动态SQL resultMap 标签: 用来描述如何从数据库结果集中来加载对象 (敲黑板!!)主管数据库的字段和实体类属性的匹配,

  • Mybatis中resultMap的使用总结

    Mybatis的介绍以及使用:http://www.mybatis.org/mybatis-3/zh/index.html resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中. resultMap包含的元素: <!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性--> <resultMap id="唯一的标识" type="映射的pojo对象&

  • Mybatis中ResultMap解决属性名和数据库字段名不一致问题

    目录 前言 1. 字段名不一致 解决方法: 第一种方式: 起别名 第二种方式: 结果集映射 resultMap 2. 多对一处理 3. 一对多处理 小结 前言 我们Pojo类的属性名和数据库中的字段名不一致的现象时有发生,简单的情况我们可以开启驼峰命名法解决大小写问题,但是遇到其它非大小写问题,我们就不得不使用Mybatis中的结果集映射resultMap. 1. 字段名不一致 数据库中的字段 我们项目中实体类的字段 public class User { private int id; pri

  • Mybatis中xml的动态sql实现示例

    目录 动态SQL简介 一.#{}与${}区别#{}表示一个占位符,使用占位符可以防止sql注入, 二.传递包装类型 三.动态sql—类型 四.动态sql—详解 (一)if 语句处理 (二)choose (when,otherwize)语句处理 (三)trim 语句处理 (四)where 语句处理 (五)foreach 语句处理 动态SQL简介 动态 SQL 是 MyBatis 的强大特性之一. 如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接

  • 解决Mybatis中foreach嵌套使用if标签对象取值的问题

    目录 foreach嵌套使用if标签对象取值问题 大体格式 解决办法 代码如下 Mybatis if 语句嵌套 要求 foreach嵌套使用if标签对象取值问题 最近做项目过程中,涉及到需要在 Mybatis 中 使用 foreach 进行循环读取传入的查询条件,动态拼接SQL语句,接口传入的查询条件格式:{"advanceSearchList":[{"searchType":10,"searchText":"12"}]} ,

  • MyBatis中resultMap和resultType的区别详解

    总结 基本映射 :(resultType)使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功.(数据库,实体,查询字段,这些全部都得一一对应)高级映射 :(resultMap) 如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系.(高级映射,字段名称可以不一致,通过映射来实现 resultType和resultMap功能类似 ,都是返回对象信息 ,但是resultMap要更强大一些

  • 详解MyBatis中主键回填的两种实现方式

    主键回填其实是一个非常常见的需求,特别是在数据添加的过程中,我们经常需要添加完数据之后,需要获取刚刚添加的数据 id,无论是 Jdbc 还是各种各样的数据库框架都对此提供了相关的支持,本文我就来和和大家分享下数据库主键回填在 MyBatis 中的两种实现思路. 原生写法 框架来源于我们学过的基础知识,主键回填实际上是一个在 JDBC 中就被支持的写法,有的小伙伴可能不知道这一点,因此这里我先来说说在 JDBC 中如何实现主键回填. JDBC 中实现主键回填其实非常容易,主要是在构造 Prepar

  • 使用mybatis的interceptor修改执行sql以及传入参数方式

    目录 mybatis interceptor修改执行sql以及传入参数 总体思路 1.Interceptor 代码实现 2.AutoConfiguration代码实现 mybatis interceptor 处理查询参数及查询结果 拦截器:拦截update,query方法 添加xml配置 mybatis interceptor修改执行sql以及传入参数 项目中途遇到业务需求更改,在查询某张表时需要增加条件,由于涉及的sql语句多而且依赖其他服务的jar,逐个修改sql语句和接口太繁杂.项目使用m

  • Mybatis中resultMap的Colum和property属性详解

    目录 resultMap的Colum和property属性 1: resultMap标签 2:使用情况 2.1 简单查询 2.2 一对一 2.3 一对多 resultMap对column和property的理解 select元素有很多属性(这里说用的比较多的) 什么时候我们知道使用resultMap,什么时候又使用resultType呢? 最后说下 resultMap的Colum和property属性 1: resultMap标签 当我们的数据库字段与实体类的属性不一致时,就需要使用该标签进行一

随机推荐