resultMap标签和sql标签的设置

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

resultMap标签和sql标签的设置

借汝之光,得以光明   2022-05-23 我要评论

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...}”

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们