SSM之Mybatis复杂的综合查询和动态sql

需求:查询用户和综合信息,需要传入信息(例如所有买一款笔记本的用户)

1、映射输入

自定义一个pojo类,把参数封装成属性,这个比较易懂。

在这里插入图片描述

补充:传入hashMap

id和username就是map的key

<select id="findUserByHashmap" parametertype="hashmap" result="user"
	select * from user where id=#{id} and username like '%${username}%'
</select>

2、输出映射

2.1 resultType
2.1.1 映射

使用resultType进行输出映射,只有在查询出来的列名和pojo对象的属性名一致,该列才能映射成功。

select id,username from .......
效果就是只有id,username这两个属性有值。
2.1.2 返回简单查询类型

查询结果为一行一列时,可以使用简单查询类型。

2.1.3 返回pojo类型和pojo列表

在mapper.xml中都一样。,resultType = pojo类路径;
在mapper.java映射接口中方法返回值不一样(动态代理对象中,自动生成):

  • 列表就用list
  • 单个对象就用User
2.2 resultMap

如果查询出来的列名和pojo属性名不一致,通过定义一个resultMap对列名和pojo属性m名之间作一个映射关系。

需求:实现select id id_,username user_ from user where id = 1

1、定义resultMap

  <!--定义resultMap
    将SELCCT id,_id FROM user  查询出来的_id 和User类中的某个属性进行映射

    type: 最终映射出来的对象,可以使用别名
    id:resultMap的标识
    -->
    <resultMap id="userResultMap"   type="user">
        <!--id:对唯一标识符的映射定义,主键-->
        <id column="_id" property="id"></id>

        <!--result:对普通查询结果的映射定义-->
        <result column="_username" property="username"/>
    </resultMap>

2、使用resultMap作为statement的输出映射类型

 <!--使用resultMap进行输出映射-->
    <select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
        SELECT id id_,username username_ FROM USER where id=#{value}
    </select>

3、在mapper接口实现方法

    //根据id查询,返回resultMap
      User findUserByIdResultMap(int id) throws Exception;

效果

 User user = userMapper.findUserByIdResultMap(1);
 System.out.println(user.toString());
out:
User [id=1, username=王五, sex=null, birthday=null, address=null]

3 、动态sql

3.1 什么是动态sql

mybati核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接组装

3.1.1 需求

用户信息的综合查询列表和用户信息查询条目数
在这里插入图片描述

有点像EL表达式,因此在java代码

3.2 生成sql代码片段,供调用

3.2.1 生成片段

在这里插入图片描述

3.2.2 调用片段

在这里插入图片描述

3.3 解析传入的多个id,通过for each进行拼接

select * from user where id in (1,2,3,4) 
select * from user where id = 1 or id = 2 or id = 3

第一步:把多个id传入,可以封装到pojo对象
在这里插入图片描述
第二步 拼接

在这里插入图片描述

第三步:测试一下

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37591656/article/details/86376100
今日推荐