MyBatis中动态SQL是一种可以根据不同条件生成不同SQL语句的技术,可以让我们根据具体的业务逻辑来拼接不同的SQL语句。
1.可以根据不同的条件生成不同的SQL语句,条件灵活
2.通过使用参数化查询或者绑定变量的方式来构建动态SQL,防止sql注入
3.动态SQL可以根据运行时的条件动态调整查询语句,优化查询
4.可以利用动态SQL来动态构建表名和字段名,实现灵活性和扩展性。
三、动态sql语句的元素及作用
用于在sql语句中添加条件语句?
根据不同的条件选择不同的查询语句
用于添加条件语句
用于对集合或数组进行循环操作
<select id="findStudentByStudent" resultType="Student" parameterType="student">
select * from Student
<!--where1=1使语句完整-->
<!--where
1=1-->
<where>
<sql>
<if test="id!=0">
AND id=#{id}
</if>
<if test="studentName!=null and studentName!=''">
AND studentName LIKE '%${studentName}%'
</if>
<if test="gender!=null and gender!=''">
AND gender=#{gender}
</if>
</sql>
</where>
</select>
????????将where条件抽取出来,使用include引用
<sql id="where_if">
<if test="id!=0">
AND id=#{id}
</if>
<if test="studentName!=null and studentName!=''">
AND studentName LIKE '%${studentName}%'
</if>
<if test="gender!=null and gender!=''">
AND gender=#{gender}
</if>
</sql>
<select id="findStudentByStudent" resultType="Student" parameterType="student">
select * from Student
<!--where
1=1-->
<where>
<include refid="where_if"></include><!--refid跟sql的id名-->
</where>
</select>
? ? ? ? 代码测试
public class TestDemo {
SqlSessionFactory ssf = null;
@Before
public void creatFactory(){
InputStream input = null;
try {
input = Resources.getResourceAsStream("SqlMapConfig.xml");
} catch (IOException e) {
e.printStackTrace();
}
ssf = new SqlSessionFactoryBuilder().build(input);
}
@Test
public void testMapper4(){
SqlSession sqlSession = ssf.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student1 = new Student();
//student1.setId(1);
student1.setStudentName("123");
//student1.setGender("男");
List<Student> students = mapper.findStudentByStudent(student1);
for (Student student : students) {
System.out.println(student.getId()+","+student.getStudentName()+","+student.getGender());
}
}