Mybatis的动态sql(一)
动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句。主要是where部分发生变化。
一、动态sql的实现
使用的是mybatis提供的标签, <if> ,<where>,<foreach>
二、定义sql的代码片段
就是复用一些语法,步骤:
1.先定义 :
<sql id="自定义名称唯一">
sql语句, 表名,字段等
</sql>
2.再使用
<include refid="id的值" />
三、if
<if>是判断条件的,语法:
<if test="判断java对象的属性值">
部分sql语句
</if>
3.1 例子
接口:
/* 使用if动态sql */
List<Student> selectStudentIF(Student stu);
xml中:
<!-- 定义sql的代码片段
1.先定义 <sql id="自定义名称唯一"> sql语句, 表名,字段等 </sql>
2.再使用 <include refid="id的值" />
-->
<sql id="studentSql">
select * from stu
</sql>
<!-- if
<if test="使用参数java对象的属性值作为判断条件,语法 属性="xxx" >
-->
<select id="selectStudentIF" resultType="com.apps.bean.Student">
<!-- 引入sql -->
<include refid="studentSql" />
where 1=1
<if test="name != null and name != '' ">
name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</select>
测试类:
@Test
public void testSelectStudentIF() {
/*
* 使用mybatis的动态代理机制,使用sqlSession.getMapper(dao接口)
* getMapper()获取dao接口对于的实现类对象
*/
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获得实现类
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student stu = new Student();
// stu.setName("张德帅");
stu.setAge(10);
//使用方法
List<Student> students = studentDao.selectStudentIF(stu);
//打印
students.forEach(stu1 -> System.out.println(stu1));
//关闭
sqlSession.close();
}
四、where
<where> 用来包含多个<if>的, 当多个if有一个成立的, <where>会自动增加一个where关键字,并去掉if中多余的and , or等。
4.1 例子
接口:
/* 使用where动态sql */
List<Student> selectStudentWhere(Student stu);
xml中:
<select id="selectStudentWhere" resultType="com.apps.bean.Student">
/* 引入sql */
<include refid="studentSql" />
<where>
<if test="name != null and name != '' ">
name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</where>
</select>
测试类:
@Test
public void testSelectStudentWhere() {
/*
* 使用mybatis的动态代理机制,使用sqlSession.getMapper(dao接口)
* getMapper()获取dao接口对于的实现类对象
*/
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获得实现类
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student stu = new Student();
// stu.setName("张德帅");
// stu.setAge(10);
//使用方法
List<Student> students = studentDao.selectStudentWhere(stu);
//打印
students.forEach(stu1 -> System.out.println(stu1));
//关闭
sqlSession.close();
}