MyBatis之动态sql

映射配置文件-resultMap属性

  • resultType可以将查询结果映射为pojo,但需要pojo类的属性名和sql查询的字段名称一致方可映 射成功。
  • 如果sql查询字段名和pojo类的属性名不一致,可以通过resultMap将字段名和属性名作一个对 应关系.
  • resultMap可以实现将查询结果映射为复杂类型的pojo,比如实现一对一查询和一对多查询。

映射配置文件-sql片段

在开发中,SQL的拼接很常见,有很多的sql具有重复性高的特点,这时最好把重复的sql抽取出 来,作为公用的sql片段。

语法

  • 定义sql片段
<sql id="片段名"> 
	sql语句 
</sql> 
  • 引用sql片段
<include refid="片段名"></include> 

案例演示

  • 查询出所有记录,返回字段值需要有:p_name、p_age
  • 模糊查询出所有记录,返回字段值需要有:p_name、p_age

动态sql之if标签

mybatis 映射文件中,if标签判断字符串相等与否

语法

<if test="OGNL表达式"> 
	sql语句 
</if> 

案例演示

  • 没有使用if标签
<select id="selectUserByUsernameAndPassword" parameterType="user" resultType="user"> 
	select * from tb_user where username = #{username} and password = # {password} 
</select> 

以上案例存在一些问题:当username和password其中任意一个没有值,那么就找不到记 录

  • 使用if标签
<select id="selectUserByUsernameAndPassword" parameterType="user" resultType="user"> 
	select * from tb_user where 1 = 1 
	<if test="username != null and username != ''"> 
		and username = #{username} 
	</if> 
	<if test="password != null and password != ''">
		and password = #{password} 
	</if> 
</select> 

动态sql之where标签

映射文件中的where标签可以省略’where 1 = 1’和’第一个if语句中的and或or’
语法

<where> 
	sql语句 
</where> 
  • 案例演示
<select id="selectUserByUsernameAndPassword" parameterType="user" resultType="user"> 
select * from tb_user 
	<where> 
		<if test="username != null and username != ''"> 
			username = #{username} 
		</if> 
		<if test="password != null and password != ''"> 
			and password = #{password} 
		</if> 
	</where> 
</select> 

动态sql之foreach标签

  • 向sql传递数组或List,mybatis使用foreach解析.
**语法** 
<foreach collection="" open="" separator="" close="" item=""> 
	sql语句 
</foreach> 
  • collection:如果是数组值为array,如果是集合值为list
  • open:设置开头
  • separator:设置间隔
  • close:设置结尾
  • item:元素名

案例演示

  • 根据一组id值查询记录
    1.使用数组
    2.使用集合
//使用数组 
<select id="selectUserListByIds1" parameterType="int[]" resultType="user"> 
	select * from tb_user 
		<where>
			<foreach collection="array" separator="," open="id in (" close=")" item="id"> 
				#{id} 
			</foreach> 
			<!‐‐ 
			<foreach collection="array" separator="or" item="id"> 
				id = #{id} 
			</foreach> 
			‐‐> 
		</where> 
</select> 

//使用集合 
<select id="selectUserListByIds2" parameterType="list" resultType="user"> 
	select * from tb_user 
	<where> 
		<foreach collection="list" separator="," open="id in (" close=")" item="id"> 
			#{id} 
		</foreach> 
	</where> 
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值