#{}和${}的区别
#{}表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换。#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。
${}表示拼接sql串,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。
1、、foreach
1 、mybatis中用foreach遍历对象时,多次使用foreach进行多次遍历,需要设置不同的变量名不能重复不然会报错。
//dao 其中@Param("list")List<Area> os和 @Param("type1")List<Devices> type1都是使用关键字in进行遍历list集合的
//List<Area>和List<Devices>都是对象集合
public List<DeviceData> findByEntryName(@Param("startDate")String startDate, @Param("lastDate")String lastDate,
@Param("dateFormat")String dateFormat,@Param("entryId")int entryId,
@Param("list")List<Area> os,@Param("length")int length,@Param("right")String right,
@Param("type1")List<Devices> type1);
//mapper
<select id="findByEntryName" resultType="com.entity.DeviceData">
SELECT dda.* FROM devicedata dda INNER JOIN (SELECT * FROM device WHERE EntryId=#{entryId}
and DeviceID in (select a.DeviceId from r_areadevice a where a.AreaId in
<foreach item="a" collection="list" separator="," open="(" close=")" >
#{a.id}
</foreach>
)
and type in
<foreach item="type1" collection="type1" separator="," open="(" close=")" >
#{type1.type}
</foreach>
) AS de
on dda.GatewaySN=de.GatewaySN and dda.Channel=de.Channel and dda.DeviceID=de.DeviceID
<!--<if test="leng==5">and right(dda.LogDate,5)='00:00'</if>-->
and right(dda.LogDate,#{length})=#{right}
and DATE_FORMAT(dda.LogDate,#{dateFormat}) BETWEEN #{startDate} and #{lastDate}
ORDER BY dda.LogDate
</select>
2、int[] 、List<String>等基本类型(String...类型的遍历)
//dao层
/**
* 根据GatewaySN查找devices
*/
public List<Devices> findBySN(@Param("list")List<String> strs);
//mapper.xml文件
<select id="findBySN" resultType="Devices">
SELECT * FROM device WHERE 1=1
<!--这句if判断可进行判断List<String>是否为null或者size为0-->
<if test="list!= null and list.size!=0">
and GatewaySN in
<foreach item="list" collection="list" separator="," open="(" close=")" >
#{list}
</foreach>
</if>
group by GatewaySN,Channel
</select>
2、对时间获取
1、取整点 如:
and right(dda.LogDate,5)='00:00' //指定右边时间格式
and right(dda.LogDate,#{length})=#{right}
2、取时间范围内,时间格式可以一直精确下去
////指定时间格式和时间段后会自动匹配格式相同的记录
and DATE_FORMAT(dda.LogDate,'%Y%m%d%H') BETWEEN '2018081509' and '2018081512'
and DATE_FORMAT(dda.LogDate,#{dateFormat}) BETWEEN #{startDate} and #{lastDate}
3、like
AND re.DbLink like concat('%',#{dbLink},'%')
4、转义字符<>
方法一
< <
<= <=
> >
>= >=
& &
' '
" "
方法二
num <![CDATA[ >= ]]> #{num}
5、Mybatis中javaType和jdbcType对应关系