广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >Mybatis 复杂对象resultMap的使用
  • 266
分享到

Mybatis 复杂对象resultMap的使用

Mybatis复杂对象复杂对象resultMap 2015-03-06 13:03:22 266人浏览 无得
摘要

目录mybatis 复杂对象resultMap下面是resultMap的定义普通属性省略说明select相关配置Model代码resultMap处理复杂映射问题Ⅰ 多对一查询:学生——老师(1) 创建实体类POJO(2) 创建学生

目录
  • mybatis 复杂对象resultMap
    • 下面是resultMap的定义
    • 普通属性省略说明
    • select相关配置
    • Model代码
  • resultMap处理复杂映射问题
    • Ⅰ 多对一查询:学生——老师
      • (1) 创建实体类POJO
      • (2) 创建学生实体类对应的接口
      • (3) 编写学生接口对应的Mapper.xml
      • (4)在核心配置类中引入Mapper
    • Ⅱ 一对多查询:老师——学生
      • (1)实体类
      • (2) 接口
      • (3)接口对应的Mapper.xml
      • (4)测试

Mybatis 复杂对象resultMap

数据对象含有普通属性,一对一对象,一对多对象(2种情况:单一主键和复合主键)

下面是resultMap的定义


 <resultMap id="GoodsResultMap" type="GoodsModelCustomize">
        <id property="goods_cd" column="goods_cd" />
        <result property="production_company_cd" column="production_company_cd" />
        <result property="production_place_cd" column="production_place_cd" />
        <result property="goods_nm_jp" column="goods_nm_jp" />
        <result property="goods_nm_en" column="goods_nm_en" />
        <result property="goods_nm_zh" column="goods_nm_zh" />
        <result property="goods_type" column="goods_type" />
        <result property="goods_package" column="goods_package" />
        <result property="upd_dttm" column="upd_dttm" />
		<association property="productioncompany" column="production_company_cd" javaType="trade.db.model.Productioncompany">
			<id property="production_company_cd" column="production_company_cd"/>
			<result property="company_nm_jp" column="company_nm_jp"/>
			<result property="company_rnm_jp" column="company_rnm_jp"/>
		</association>
		<collection property="goodsnutrientList" column="goods_cd" ofType="trade.db.model.Goodsnutrient" select="getGoodsnutrient" />
		<collection property="liquorgoodsccicList" column="goods_cd" ofType="trade.db.model.Liquorgoodsccic" select="getLiquorgoodsccic">
       		<id property="goods_cd" column="goods_cd" />
			<id property="ccic_item_cd" column="ccic_item_cd"/>
			<result property="ccic_item_val1" column="ccic_item_val1"/>
		</collection>
		<collection property="projectgoodsList" column="goods_cd" ofType="trade.db.model.Projectgoods" select="getProjectgoods">
			<id property="project_goods_cd" column="project_goods_cd"/>
			<result property="project_cd" column="project_cd"/>
			<result property="goods_cd" column="goods_cd"/>
		</collection>
    </resultMap>
    <resultMap id="GoodsnutrientResultMap" type="Goodsnutrient">
        <id property="goods_cd" column="goods_cd" />
        <id property="nutrient_item_cd" column="nutrient_item_cd" />
        <result property="sort_no" column="sort_no" />
        <result property="nutrient_value" column="nutrient_value" />
        <result property="nutrient_nrv" column="nutrient_nrv" />
        <result property="upd_dttm" column="upd_dttm" />
    </resultMap>

普通属性省略说明

  • 一对一属性productioncompany
  • 一对多属性goodsnutrientList(复合主键,返回的复杂对象内有数据)
  • 一对多属性liquorgoodsccicList(复合主键,返回的复杂对象内没有数据)
  • 一对多属性projectgoodsList(单一主键,返回的复杂对象内有数据)

select相关配置


    <select id="getGoodsnutrient" parameterType="String" resultMap="GoodsnutrientResultMap">
        SELECT 
        	m_goods_nutrient.*
        FROM m_goods_nutrient
        <where>
        	m_goods_nutrient.goods_cd = #{goods_cd}
        	AND m_goods_nutrient.del_flg = '0'
        </where>
    </select>
    <select id="getLiquorgoodsccic" parameterType="String" resultType="trade.db.model.Liquorgoodsccic">
        SELECT 
        	m_liquorgoods_ccic.*
        FROM m_liquorgoods_ccic
        <where>
        	m_liquorgoods_ccic.goods_cd = #{goods_cd}
        	AND m_liquorgoods_ccic.del_flg = '0'
        </where>
    </select>
   <select id="getProjectgoods" parameterType="String" resultType="trade.db.model.Projectgoods">
        SELECT 
        	t_project_goods.*
        FROM t_project_goods
        <where>
        	t_project_goods.goods_cd = #{goods_cd}
        	AND t_project_goods.del_flg = '0'
        </where>
    </select>
   <select id="findByPrimaryKey" parameterType="String" resultMap="GoodsResultMap">
        SELECT 
            m_goods.*,
        	m_production_company.*,
            now() AS SELECT_TIME
        FROM m_goods
        LEFT JOIN
        	m_production_company
        	ON m_goods.production_company_cd = m_production_company.production_company_cd
        	AND m_production_company.del_flg = '0'
        WHERE
              m_goods.goods_cd = #{primary_key}
        	AND m_goods.del_flg = '0'
    </select>
  • 通过findByPrimaryKey方法获取普通属性和1对1对象属性
  • 通过getGoodsnutrient方法获取1对多复合主键的属性,注意返回类型的配置为resultMap=“GoodsnutrientResultMap”(返回的对象的List属性内有数据)
  • 通过getLiquorgoodsccic方法获取1对多复合主键的属性,此处的返回类型为 resultType=“trade.db.model.Liquorgoodsccic”(返回的对象的List属性内没有数据)
  • 通过getProjectgoods方法获取1对多单一主键的属性,此处的返回类型为resultType=“trade.db.model.Projectgoods”(返回的对象的List属性内有数据)

Model代码


public class GoodsModelCustomize extends Goods {
	
	private Productioncompany productioncompany;
	public Productioncompany getProductioncompany() {
		return productioncompany;
	}
	public void setProductioncompany(Productioncompany productioncompany) {
		this.productioncompany = productioncompany;
	}
	
	private List<Goodsnutrient> goodsnutrientList;
	public List<Goodsnutrient> getGoodsnutrientList() {
		return goodsnutrientList;
	}
	public void setGoodsnutrientList(List<Goodsnutrient> goodsnutrientList) {
		this.goodsnutrientList = goodsnutrientList;
	}
	
	private List<Liquorgoodsccic> liquorgoodsccicList;
	public List<Liquorgoodsccic> getLiquorgoodsccicList() {
		return liquorgoodsccicList;
	}
	public void setLiquorgoodsccicList(List<Liquorgoodsccic> liquorgoodsccicList) {
		this.liquorgoodsccicList = liquorgoodsccicList;
	}
	
	private List<Projectgoods> projectgoodsList;
	public List<Projectgoods> getProjectgoodsList() {
		return projectgoodsList;
	}
	public void setProjectgoodsList(List<Projectgoods> projectgoodsList) {
		this.projectgoodsList = projectgoodsList;
	}
}

普通属性继承与Goods代码省略,上述属性productioncompany,goodsnutrientList和projectgoodsList有数据,但是liquorgoodsccicList没有数据

因此,当返回对象内有1对多的List属性,同时此list为复合主键的话,推荐使用resultMap来对返回数据映射。

resultMap处理复杂映射问题

在这里插入图片描述

  • association:关联(多对一的情况)
  • collection: 集合(一对多的情况)
  • javaType: 用来指定实体类中属性的类型。
  • ofType: 用来指定映射到List或集合中POJO的类型,泛型的约束类型。

Ⅰ 多对一查询:学生——老师

数据库表:


CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher(`id`, `name`) VALUES (1, '王老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRaiNT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

在这里插入图片描述

(1) 创建实体类POJO


@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

@Data
public class Teacher {
    private int id;
    private String name;
}

(2) 创建学生实体类对应的接口


public interface StudentMapper {
    //查询所有学生的信息
    List<Student> getStudent();
    List<Student> getStudent2();
}

(3) 编写学生接口对应的Mapper.xml

为了达到和接口在同一个包中的效果,在resource文件夹下新建包结构com.glp.dao:

在这里插入图片描述


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "Http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.glp.dao.StudentMapper">
<!--按照结果查询——联表查询-->
    <select id="getStudent2" resultMap="StudentMap2">
         select s.id sid,s.name sname,t.name tname from student s, teacher t where s.tid=t.id;
    </select>
    <resultMap id="StudentMap2" type="Student">
         <result property="id" column="sid"/>
         <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
    <!--按照查询嵌套处理——子查询-->
        <select id="getStudent" resultMap="StudentMap" >
           select * from student;
        </select>
    <resultMap id="StudentMap" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂属性:对象association, 集合collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
        
        <select id="getTeacher" resultType="Teacher">
            select * from teacher where id = #{id};
        </select>
</mapper>

在多对一查询中,需要用到teacher这个表,每个学生都对应着一个老师。而property只能处理单个属性,像teacher这种复杂属性(内含多个属性)需要进行处理。处理复杂对象要用association 。

方式一:联表查询(直接查出所有信息,再对结果进行处理)


   <resultMap id="StudentMap2" type="Student">
         <result property="id" column="sid"/>
         <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

直接查询出学生和老师,然后用association去取老师里面的属性property。

方式二:子查询(先查出学生信息,再拿着学生中的tid,去查询老师的信息)


  <resultMap id="StudentMap" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂属性:对象association-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
        
        <select id="getTeacher" resultType="Teacher">
            select * from teacher where id = #{id};
        </select>

在resultMap中引入属性association,通过javaType指定property="teacher"的类型,javaType="Teacher"。通过select引入子查询(嵌套查询)。

在这里插入图片描述

这里是拿到学生中的tid,去查找对应的老师。

(4)在核心配置类中引入Mapper

db.properties:数据库连接参数配置文件


driver = com.Mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&chracterEncoding=utf8
username =root
passWord =mysql

mybatis.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">
<configuration>
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="mysql"/>
    </properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <typeAlias type="com.glp.POJO.Student" alias="Student"/>
        <typeAlias type="com.glp.POJO.Teacher" alias="Teacher"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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 class="com.glp.dao.StudentMapper"/>
        <mapper class="com.glp.dao.TeacherMapper"/>
    </mappers>
</configuration>

注意:

要保证接口和Mapper.xml都在同一个包中。

(5) 测试


public class UserDaoTest {
    @Test
    public void getStudent(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> list = mapper.getStudent();
        for (Student stu:list ) {
            System.out.println(stu);
        }
        sqlSession.close();
    }
    @Test
    public void getStudent2(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> list = mapper.getStudent2();
        for (Student stu:list ) {
            System.out.println(stu);
        }
        sqlSession.close();
    }
}

Ⅱ 一对多查询:老师——学生

在这里插入图片描述

(1)实体类


@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

(2) 接口


package com.glp.dao;
public interface TeacherMapper {
    Teacher getTeacher(@Param("tid") int id);
    Teacher getTeacher2(@Param("tid") int id);
}

(3)接口对应的Mapper.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.glp.dao.TeacherMapper">
  <!--方式一          =======================                  -->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname, t.id tid from
        student s ,teacher t where s.tid = t.id and t.id = #{tid};
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    <!--方式二          =======================                  -->
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid};
         <!--这里的tid和接口中指定的属性名相同-->
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
     <result property="id" column="id"/>
        <result property="name" column="name"/>
           <!--上面的两个可以省略-->
        <collection property="students"  column="id" javaType="ArrayList" ofType="Student"  select="getStuById"/>
    </resultMap>
    <select id="getStuById" resultType="Student">
        select * from student where tid=#{tid};
           <!--查询老师对应的学生,#{tid}-->
    </select>
</mapper>

方式一:联表查询,需要写复杂SQL

collection 用来处理集合,ofType用来指定集合中的约束类型

联合查询时,查询出所以结果,然后再解析结果中的属性,将属性property赋予到collection中。

方式二:子查询,需要写复杂映射关系

在这里插入图片描述

在这里插入图片描述

查询学生时,需要拿着老师的id去查找,column用来给出老师的id。

(4)测试:


package com.glp.dao;
public class UserDaoTest {
    @Test
    public void getTeacher(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
    @Test
    public void getTeacher2(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher2(1);
        System.out.println(teacher);
        sqlSession.close();
    }
}

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

--结束END--

本文标题: Mybatis 复杂对象resultMap的使用

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

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

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

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

下载Word文档
猜你喜欢
  • Mybatis 复杂对象resultMap的使用
    目录Mybatis 复杂对象resultMap下面是resultMap的定义普通属性省略说明select相关配置Model代码resultMap处理复杂映射问题Ⅰ 多对一查询:学生——老师(1) 创建实体类POJO(2) 创建学生...
    99+
    2015-03-06
    Mybatis复杂对象 复杂对象resultMap
  • mybatis 如何利用resultMap复杂类型list映射
    mybatis resultMap复杂类型list映射 映射泛型为对象 xml <resultMap id="internetDataDTO" type="com.mdm....
    99+
    2022-11-12
  • mybatis怎么利用resultMap复杂类型list映射
    这篇文章主要介绍“mybatis怎么利用resultMap复杂类型list映射”,在日常操作中,相信很多人在mybatis怎么利用resultMap复杂类型list映射问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家...
    99+
    2023-06-20
  • mybatis resultmap怎么为对象赋值的调用顺序
    这篇文章主要介绍“mybatis resultmap怎么为对象赋值的调用顺序”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“mybatis resultmap怎么为对象赋值的调用顺...
    99+
    2023-06-29
  • Mybatis中resultMap的使用总结
    Mybatis的介绍以及使用:http://www.mybatis.org/mybatis-3/zh/index.html resultMap是Mybatis最强大的元素,它可以将查...
    99+
    2022-11-12
  • Mybatis之@ResultMap,@Results,@Result注解的使用
    目录Mybatis注解@Results、@Result、@ResultMap问题方法一方法二mybatis注释使用resultMap对应的注释,及对应注解Results、Result...
    99+
    2022-11-12
  • Mybatis resultMap标签继承、复用、嵌套的方法
    本篇内容主要讲解“Mybatis resultMap标签继承、复用、嵌套的方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Mybatis resultMap标签继承、复用、...
    99+
    2023-06-29
  • 解析mybatis-plus中的resultMap简单使用
    不一致,那么用来接收查询出来的result对应的数据将会是Null,如果不使用resultMap,那么一般为了避免pojo对象对应的属性为Null,会采用SQL语句中的别名,将查询出...
    99+
    2022-11-12
  • Mybatis的@ResultMap,@Results,@Result注解怎么使用
    本篇内容主要讲解“Mybatis的@ResultMap,@Results,@Result注解怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Mybatis的@ResultMap,@Resu...
    99+
    2023-06-21
  • MyBatis resultMap id标签的错误使用方式
    目录MyBatis resultMap id标签的错误使用本节的问题主要是我对mybatis id标签的错误使用resultMap标签的使用规则自定义结果映射规则associatio...
    99+
    2022-11-13
  • django如何获取ajax的post复杂对象
    这篇文章给大家分享的是有关django如何获取ajax的post复杂对象的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、django的request中post对象为空(即获取不到前台ajax传送的post对象)...
    99+
    2023-06-08
  • Spring复杂对象创建的方式小结
    在Spring中,对于简单类型的创建,我们可以使用set注入和构造注入。但是对于复杂类型的如何创建? 什么是复杂类型,比如连接数据库的Connection对象,以及Mybatis中的...
    99+
    2022-11-12
  • MyBatis-Plus中如何使用ResultMap的方法示例
    目录问题说明解决方法自定义@AutoResultMap注解MyBatis-Plus (简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、...
    99+
    2022-11-12
  • mybatis使用resultMap获取不到值的解决方案
    目录mybatis resultMap获取不到值问题描述原因及解决方法Mybatis 从数据库中获取值为null ResultMap要解决的问题:属性名和字段名不一致解决方法mybatis resultMap获取不到值 <...
    99+
    2017-04-23
    mybatis resultMap resultMap获不到值
  • Mybatis Lombok使用方法与复杂查询介绍
    目录基本要点1、Lombok2、多对一处理3、一对多基本要点 1、Lombok 作用:在我们的实体类中,我们再也不需要声明get、set、有参无参等方法,统统可以通过Lombok注解...
    99+
    2022-11-13
  • Mybatis Plus使用queryWrapper怎么实现复杂查询
    这篇文章主要讲解了“Mybatis Plus使用queryWrapper怎么实现复杂查询”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Mybatis Plus使用queryWrapper怎么...
    99+
    2023-06-26
  • 怎么在SpringMVC中接收复杂的集合对象
    这篇文章将为大家详细讲解有关怎么在SpringMVC中接收复杂的集合对象,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。页面js代码:Js代码var idList =&nb...
    99+
    2023-05-30
    springmvc
  • 利用SpringMVC接收复杂对象和多个文件(前端使用JQuery)
    目录前言将要使用的类和配置前端页面和JS文件HTML页面JS文件后台使用SpringMVC接收数据使用SpringMVC参数绑定使用传统的HttpServletRequest接收前言...
    99+
    2022-11-13
    SpringMVC接收复杂对象 SpringMVC接收多个文件 SpringMVC接收
  • Java Mybatis使用resultMap时,属性赋值顺序错误的巨坑
    目录Mybatis使用resultMap属性赋值顺序错误ids是后加入的字段 resultMap中是这样写的解决办法Mybatis使用resultMap时需注意Mybati...
    99+
    2022-11-13
  • 复杂JSON字符串转换为Java嵌套对象的实现
    目录背景方法预备工作构建对象模型使用jackson 库解析使用GSON解析不含列表的嵌套对象背景 实际开发中,常常需要将比较复杂的 JSON 字符串转换为对应的 Java 对象。这里...
    99+
    2022-11-12
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作