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