基本也都是映射文件的一些需要注意的问题:
第一个:写动态sql的时候,有个查询条件需要匹配模糊查询:
<select id="selectAllEmpTrainingRecord" resultMap="empTrainMap">
select * from course t
<where>
<if test="course != null" >
<bind name="courseName" value="'%' + course + '%'"/>
t.courseName like #{courseName}
</if>
</where>
order by t.startDate desc
</select>
网上学习了下,有三种方式
1, 字段名 like %值%
<select id="selectAllEmpTrainingRecord" resultMap="empTrainMap">
select * from course t
<where>
<if test="course != null" >
t.courseName like '%${courseName}%'
</if>
</where>
order by t.startDate desc
</select>
该种方式传参必须用${}不能用#{},所以这样写的弊端就是不安全,不能防sql注入
2,CONCAT()拼接%
例:
<select id="selectAllEmpTrainingRecord" resultMap="empTrainMap">
select * from course t
<where>
<if test="course != null" >
t.courseName like CONCAT('%',CONCAT(#{name},'%'))
</if>
</where>
order by t.startDate desc
</select>
注意: 拼接时%必须加引号
3,使用元素:bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文
<select id="selectAllEmpTrainingRecord" resultMap="empTrainMap">
select * from course t
<where>
<if test="course != null" >
<bind name="courseName" value="'%' + course + '%'"/>
t.courseName like #{courseName}
</if>
</where>
order by t.startDate desc
</select>
小结:
以上三种方式的区别:
一是数据不安全的,所以最好不用一方法
使用二与三的区别:concat适用于mysql和sql server数据库,oracle数据库不支持,bind适用于mysql,sql server,oracle,所以为了通用性或避免因更换数据库带来的不便,推荐使用第三种bind为好。
再补充一种跟上面第一种类似的方法:
暂称第四种:
4,直接传入带有%实参%的参数
public void selectBykeyWord(String keyword) {
String id = “%” + keyword + “%”;
String roleType = “%” + keyword + “%”;
String roleName = “%” + keyword + “%”;
userDao.selectBykeyWord(id,roleName,roleType);
}
在Mapper层指定各个参数的别名
List<RoleEntity> selectBykeyWord(@Param("id") String id,@Param("roleName") String roleName,@Param("roleType") String roleType);
然后映射文件:
<select id="selectBykeyWord" parameterType="string" resultType="com.why.mybatis.entity.RoleEntity">
SELECT
*
FROM
t_role
WHERE
role_name LIKE #{roleName}
OR id LIKE #{id}
OR role_type LIKE #{roleType}
</select>
执行出来的SQL语句:
SELECT
*
FROM
t_role
WHERE
role_name LIKE ‘%why%’
OR id LIKE ‘%why%’
OR role_type LIKE ‘%why%’;
第二个:时间区间判断问题
在有时候的需求中,我们需要获取某一个时间段的数据,这时候就要用到判断时间段;
例子:
<select id="selectEmpTrainingByName" resultMap="empTrainMap">
select * from 培训记录表_主表 t
inner join 培训记录表_明细 t1
on t.ExcelServerRCID = t1.ExcelServerRCID
<where>
<if test="course != null and course != ''">
and t.课程名称=#{course}
</if>
<if test="empName != null and empName !=''">
and t1.姓名=#{empName}
</if>
<if test="startDate != null and startDate !=''">
and t.培训日期 >= #{startDate}
</if>
<if test="endDate != null and endDate !=''">
and #{endDate} >= t.培训日期
</if>
</where>
order by t.培训日期 desc
</select>
开始的时候判断时间区间我是这么写的
后面查到说mybaits映射文件中不能写 <= 号 ,所有我后来改成这样:
报错立马消失。
未完,待续。。。。。。