自定义结果集-resultMap

时间:2021-08-23
本文章向大家介绍自定义结果集-resultMap,主要包括自定义结果集-resultMap使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

自定义结果集-resultMap

1.新建一个数据库表

2.创建javaBean

package com.yicurtain.bean;

public class Cat {
    private Integer id;
    private String name;
    private Integer gender;
    private Integer age;

    public Cat() {
    }

    public Cat(Integer id, String name, Integer gender, Integer age) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getGender() {
        return gender;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender=" + gender +
                ", age=" + age +
                '}';
    }
}

3.创建一个CatDao

package com.yicurtain.dao;

import com.yicurtain.bean.Cat;

public interface CatDao {
    public Cat getCatById(Integer id);
}

4.配置CatDao.xml

<?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.yicurtain.dao.CatDao">
<select id="getCatById" resultMap="myCat">
    select * from t_cat where id=#{id}
</select>
    <!--自定义某个javaBean的封装规则
type:自定义规则的Java类型
id:唯一id方便引用
  -->
    <resultMap id="myCat" type="com.yicurtain.bean.Cat">
        <result column="id" property="id"></result>
        <result column="cName" property="name"></result>
        <result column="cGender" property="gender"></result>
        <result column="cAge" property="age"></result>
    </resultMap>
</mapper>

5.测试

    //测试自定义结果集
    @Test
    public void testCat(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            CatDao catDao = sqlSession.getMapper(CatDao.class);
            Cat catById = catDao.getCatById(1);
            System.out.println(catById);

        } finally {

            sqlSession.close();
        }

    }

原文地址:https://www.cnblogs.com/yicurtain/p/15174797.html