mybatis动态sql代码片段

在sql语句中,查询的时候时候不要使用*号,*是查询所有,这样如果改动表,或者对查询的效率都有非常大的影响,而查询的语句更推荐些出相对应的字段
在MyBatis中有很多的查询语句,如果每个都列出字段,显得十分麻烦,这样就可以有include的用法。
在mybatis中通过sql代码片段可以提高代码的重用性。
在mybatis中通过 和 标签定义sql代码片段,用来封装SQL语句, 来调用。
创建UserMapper.xml
1、创建动态SQL

<!-- /*动态sql之代码片段 :复用sql语法 id唯一*/-->
<sql id="userSql">
 	select id,name,age from user
</sql>

2、使用
sql 标签中id值于include 标签中的refid值相对应,include 标签通过refid值调用相对应的sql 标签中的sql语句,以达到提高代码的重用性,多个sql的代码嵌套可以嵌套

<select id="selectUser" resultType="com.gx.pojo.User">
		/*动态sql之代码片段 :复用sql语法 id唯一*/
		<include refid="userSql"></include>
		where
		<if test="name !=null and name !=''">
    			name = #{name}
		</if>
		<if test="age>0">
    			and age > #{age}
	 </if>
</select>
<!--where-->
<select id="selectUserwhere" resultType="com.gx.pojo.User">
	<include refid="userSql"></include>
		<where>
    		<if test="name !=null and name !=''">
        		name = #{name}
    		</if>
    		<if test="age>0">
       		 and age > #{age}
   		 </if>
		</where>
</select>

3: 可以引用或者嵌套进入其他的xml
嵌套:准备一个mapper.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.gx.dao.Userdao">
   		 <sql id="vals">(1,2,3,4)</sql>
    		<!--注意以下写了命名空间com.gx.dao.Userdao,防止Mapper.xml中引用时报错-->
    		<sql id="where"> STATUS IN <include refid="com.gx.dao.Userdao.vals"/></sql>
	</mapper>

嵌套进UserMapper.xml

<sql id="liuser"> 
SELECT * FROM TEST WHERE 
<include refid="com.test.BaseDAO.where"/>
</sql>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值