在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>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐