#{}和${}的區別
#{}表示一個佔位符號,通過#{}可以實現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對應關係