mybatis动态SQL
动态sql可以增加sql的灵活性, 也是mybatis最大的优势功能 (更多标签可查看官方文档)
if 和 where标签
格式:
<if test="判定条件"> -- 判定条件为true,则执行标签内部的sql语句,否则不执行.
sql语句
</if>
例如: 查询指定工资范围的员工信息
<select id="findBySal12" resultType="com.tedu.pojo.Emp">
select * from emp
where 1 = 1
<if test="minsal != null">
and salary >= #{minSal}
</if>
<if test="maxSal != null">
and salary <= #{maxSal}
</if>
</select>
使用1 = 1 是为了防止两个if判断都不生效, 防止sql出现错误
当然也可以使用这种方式: 使用<where>
标签来替换where
select * from emp
<where>
<if test="minsal != null">
and salary >= #{minSal}
</if>
<if test="maxSal != null">
and salary <= #{maxSal}
</if>
</where>
foreach标签
格式:
<foreach collection="类型" open="开始标志" item="每个元素名字" separator="分隔符" close="结尾标志">
#{每个元素名字}
</foreach>
例如: 根据员工的id批量删除员工信息传过来的参数是一个Ingeger[] ids的数组Integer ids = {1, 3, 5, 7}
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="array" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</delete>
执行后这个sql就是:
delete from emp where id in (1, 3, 5, 7)
SQL语句中的特殊符号
示例:添加一个查询功能:查询薪资小于3500的所有员工。
1、编辑EmpMapper.xml文件, 添加查询对应的sql.
<!-- 练习12: 根据薪资查询员工信息 -->
<select id="findBySal" resultType="com.tedu.pojo.Emp">
select * from emp
where 2=2
<if test="minSal != null">
and salary >= #{minSal}
</if>
<if test="maxSal != null">
and salary <= #{maxSal}
</if>
</select>
2、但在书写完后,xml文件提示有错误:
原来,小于号(<)在xml文件中是特殊字符,被xml文件当成了标签的开始符号。
3、解决方法:可以使用 <
代替 <
,例如:
<select id="findBySal" resultType="com.tedu.pojo.Emp">
select * from emp
where 2=2
<if test="minSal != null">
and salary >= #{minSal}
</if>
<if test="maxSal != null">
and salary <= #{maxSal}
</if>
</select>
或者是将特殊符号包含在CDATA区( )中,这是因为放在CDATA区中的内容,只会被xml解析器当作普通文本来处理。而不是被当成标签的一部分处理。
<!-- 查询薪资小于3500的所有员工 -->
<select id="findBySal" resultType="com.tedu.pojo.Emp">
select * from emp
where 2=2
<if test="minSal != null">
and salary >= #{minSal}
</if>
<if test="maxSal != null">
and salary <![CDATA[ <= ]]> #{maxSal}
</if>
</select>
jdbc.properties文件
在开发中,通常我们会将连接数据库的配置信息单独放在一个properties文件中(方便管理和维护),
然后在MyBatis的mapper文件中引入properties文件的配置信息即可!
1、在src目录下创建一个名称为jdbc.properties的文件
2、jdbc.properties文件内容如下:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/库名?characterEncoding=utf-8
jdbc.username=root
jdbc.password=密码
3、在mybatis-config.xml文件中引入jdbc.properties文件
1、其中 <properties resource="jdbc.properties"/>
标签用于引入jdbc.properties文件,默认到classpath即类目录下寻找指定的文件;
properties 标签写在configuration标签下
2、properties标签上value属性中配置的 ${jdbc.xxx}:
${jdbc.driver}
:其实就是jdbc.properties文件中的 jdbc.driver的值,即:
com.mysql.jdbc.Driver
${jdbc.url}
:其实就是jdbc.properties文件中的 jdbc.url的值,即:
jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=utf-8
${jdbc.username}
:其实就是jdbc.properties文件中的 jdbc.username的值,即:
root
${jdbc.password}
:其实就是jdbc.properties文件中的 jdbc.password的值,即:
1234