广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Mybatis中resultMap标签和sql标签的设置方式
  • 714
分享到

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

2024-04-02 19:04:59 714人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录resultMap标签和sql标签的设置1、项目目录2、数据库中的表的信息3、配置文件的信息4、User类5、IUserDao接口6、mybatisTest7、运行结果resul

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 {
    
    List<User> findAll();
    
    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...}”

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

--结束END--

本文标题: Mybatis中resultMap标签和sql标签的设置方式

本文链接: https://www.lsjlt.com/news/162036.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Mybatis中resultMap标签和sql标签的设置方式
    目录resultMap标签和sql标签的设置1、项目目录2、数据库中的表的信息3、配置文件的信息4、User类5、IUserDao接口6、MybatisTest7、运行结果resul...
    99+
    2022-11-12
  • MyBatis resultMap id标签的错误使用方式
    目录MyBatis resultMap id标签的错误使用本节的问题主要是我对mybatis id标签的错误使用resultMap标签的使用规则自定义结果映射规则associatio...
    99+
    2022-11-13
  • Mybatis resultMap标签继承、复用、嵌套方式
    目录resultMap标签继承、复用、嵌套定义表与实体类表实体类定义与表映射的 resultMap继承、复用、嵌套使用resultMap需要注意的地方resultMap标签继承、复用...
    99+
    2022-11-13
  • MyBatis中的ResultMap的association和collection标签详解
    目录一、前言二、ResultMap 的属性列表三、resultMap标签介绍四、id & result标签参数详解五、association标签常用参数详解六、collect...
    99+
    2022-11-13
    MyBatis association和collection标签 MyBatis  ResultMap
  • Mybatis resultMap标签继承、复用、嵌套的方法
    本篇内容主要讲解“Mybatis resultMap标签继承、复用、嵌套的方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Mybatis resultMap标签继承、复用、...
    99+
    2023-06-29
  • css标签与标签设置距离的方法
    这篇文章给大家分享的是有关css标签与标签设置距离的方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。在css中,可以使用margin系列属性来设置标签与标签间的距离。margin属性用于设置元素的外边距,是自身...
    99+
    2023-06-06
  • mybatis中foreach嵌套if标签方式
    目录mybatis foreach嵌套if标签xml文件 $和 #的区别union与union all区别mybatis if和foreach嵌套 (同一个列,不...
    99+
    2022-11-13
  • Mybatis mapper标签中配置子标签package的坑及解决
    目录mapper标签中配置子标签package的坑Mybatis中mappers标签介绍配置方式1.接口所在包2.相对路径配置3.类注册引入4.使用URL绝对路径方式引入(不用)使用...
    99+
    2022-11-12
  • MyBatis typeAliases元素标签(含注解方式)及其属性、设置方式
    目录typeAliases元素标签及其属性、设置简介通过单个定义别名的方式通过包扫描的方式采用注解的方式常见的 Java 类型内建的相应的类型别名typeAliases和packag...
    99+
    2022-11-12
  • html设置a标签居中的方法
    本篇内容介绍了“html设置a标签居中的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!html设置a标...
    99+
    2022-10-19
  • MyBatis中foreach标签的collection属性的取值方式
    目录foreach标签的collection属性的取值传的是List列表传的是Array数组传的是Mapcollection属性总结MyBatis使用foreach标签报错原因解决方...
    99+
    2022-11-13
  • mybatis中sql语句CDATA标签的用法说明
    sql语句CDATA标签的用法 CDATA 指的是不应由 XML 解析器进行解析的文本数据(Unparsed Character Data)。 在 XML 元素中,"<" 和 ...
    99+
    2022-11-12
  • mybatis中sql语句CDATA标签的用法介绍
    这篇文章主要介绍“mybatis中sql语句CDATA标签的用法介绍”,在日常操作中,相信很多人在mybatis中sql语句CDATA标签的用法介绍问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”mybatis...
    99+
    2023-06-20
  • Mybatis配置之properties和settings标签的用法
    Mybatis properties标签和settings标签 本次将讲述mybatis的配置,主要的配置是基于mybatis的配置文件来进行配置的,其配置文件并不复杂 如下面的例子...
    99+
    2022-11-12
  • DreamWeaver设置行内标签的方法
    这篇文章给大家分享的是有关DreamWeaver设置行内标签的方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。新建一个DreamWeaverwn文件,鼠标在body标签中间点击一下在body标签中输入h2标签,...
    99+
    2023-06-08
  • css设置所有标签的方法
    本篇内容主要讲解“css设置所有标签的方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“css设置所有标签的方法”吧! 设置方法:1...
    99+
    2022-10-19
  • Trim标签在Mybatis中的使用方法
    Trim标签在Mybatis中的使用方法?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。具体代码如下所示:<update id="updateAu...
    99+
    2023-05-31
    mybatis trim
  • MyBatis insert语句返回主键和selectKey标签方式
    目录insert语句返回主键和selectKey标签1.主键自增的情况2.Oracle中用Sequence获取主键MyBatis insert语句key的生成和返回1.使用...
    99+
    2022-11-12
  • HTML5中如何在title标题标签里设置小图标的方法
    小编给大家分享一下HTML5中如何在title标题标签里设置小图标的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一张网页,如果标题只有文字,那会显得特别单调...
    99+
    2023-06-09
  • matplotlib设置坐标轴标签和间距的实现
    目录xlim、ylimxticks、yticks总结我们今天继续matplotlib作图教程。 在上周的文章当中我们介绍了如何通过xlabel和ylabel设置坐标轴的名称,以及这两...
    99+
    2022-11-12
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作