查询数据时数据库表字段名和实体表属性名不一样,不能自动封装数据解决方法:
¤ 起别名:在映射文件查询语句里对不一样的列名起别名,让别名和实体类属性名一样 注:这种方式太麻烦
¤ 定义sql片段:在映射文件里定义片段,然后在查询语句里引用 注:不灵活
<sql id="xxx">
字段名1, 字段名2 as 别名1, 字段名3 as 别名2, 字段名4, ......
</sql>
<seclect id="seclectAll" resultType="brand">
select
<include refid="xxx" />
from 表名;
</select>
¤ 定义resultMap
<resultMap id="xxx" type="brand">
<id column=表里列名 property=实体类属性名 /> 注:用于主键别名映射
<result column=表里列名 property=实体类属性名 /> 注:用于普通列别名映射
.........
</resultMap>
<seclect id="seclectAll" resultMap="xxx">
select
*
from 表名;
</select>
条件查询时参数传递:
¤ #{} 注:会将其替换成?,防止SQL注入
¤ ${} 注:拼接SQL语句,不能防止SQL注入
¤ 例:
<seclect id="seclectAll" resultMap="xxx">
select *
from 表名 where id = #{id}或者${id};
</select>
查询语句特殊字符处理:例:<
¤ 转义
¤ CDATA区:
<seclect id="seclectAll" resultMap="xxx">
select *
from 表名 where id
<![CDATA[<]]>
#{id};
</select>
多条件查询语句:
¤ 散装参数:使用@Param注解,注解的名字要和映射文件里对应查询语句的参数占位符一致
♦ List<Band> selectByCondition(@Param("status")int status, @Param("companyName")string companyName, @Param("brandName")string brandName)
¤ 对象参数:对象属性名称要和映射文件里对应查询语句的参数占位符一致
♦ List<Band> selectByCondition(Brand brand)
¤ map集合参数:
♦ List<Band> selectByCondition(Map map)
♦ 要求:映射文件里对应查询语句的参数占位符要和键值对的key一致
¤ 如果查询涉及到模糊查询之类的,在参数接收后,需要在接口方法里先处理,加上一些模糊语法,再传入MyBatis
多条件动态条件查询
¤ 例:
<seclect id="seclectByCondition" resultMap="xxx">
select *
from 表名
where
<if test="status != null">
status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName}
</if>
</select>
¤ if语句会出现的问题:当第一个条件不存在,语法就会出错
♦ 解决方法一:每个if标签的sql语句前都加上and,然后再where 后面加上 1=1
♦ 解决方法二:使用<where></where>标签替换where
<seclect id="seclectByCondition" resultMap="xxx">
select *
from 表名
<where>
<if test="status != null">
status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName}
</if>
</where>
</select>
单条件动态条件查询:从多个条件中选择一个,类似于switch语句
¤ choose(when, othwrwise)
<seclect id="seclectByCondition" resultMap="xxx">
select *
from 表名
where
<choose>
<when test="status != null">
status = #{status}
</when>
<when test="companyName != null and companyName != '' ">
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != '' ">
brand_name like #{brandName}
</when>
<otherwise> 注:可以没有
1=1
</otherwise>
</chhoose>
</select>
浙公网安备 33010602011771号