Mybatis中各種操作總結
阿新 • • 發佈:2021-07-08
Mybatis中各種操作總結
1.大於等於和小於等於的寫法
大於等於
<![CDATA[ >= ]]>
小於等於
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and create_date_time <![CDATA[ <= ]]> #{endTime}
2.引數遍歷
index屬性:記錄遍歷的次數。通過#{index}可以獲取到是第幾次遍歷
1. 傳入的引數為list的時候 對應的Dao中的Mapper檔案是: public List<User> selectByIds(List<Integer> ids); xml檔案程式碼片段: <select id="selectByIds" resultType="com.txw.pojo.User"> select * from user where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select> 2. 傳入的引數為Array的時候 對應的Dao中的Mapper檔案是: public List<User> selectByIds(int[] ids); xml檔案程式碼片段: <select id="selectByIds" resultType="com.txw.pojo.User"> select * from user where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select> 3. 傳入的引數為Map的時候 對應的Dao中的Mapper檔案是: public List<User> selectByIds(Map<String, Object> params); xml檔案程式碼片段: <select id="selectByIds" resultType="com.txw.pojo.User"> select * from user where id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select> map的時候需要注意的是:collection的值“ids”是儲存在map中的key(比如:map.put("ids",ids));尤其需要注意;
3.插入之後返回特定欄位
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"> <!-- 將插入資料的主鍵返回,返回到user物件中 =================SELECT LAST_INSERT_ID():得到剛insert進去記錄的主鍵值,只適用與自增主鍵 keyProperty:將查詢到主鍵值設定到parameterType指定的物件的哪個屬性 order:SELECT LAST_INSERT_ID()執行順序,相對於insert語句來說它的執行順序 resultType:指定SELECT LAST_INSERT_ID()的結果型別 --> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO user(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address}) </insert>
4.sql複用
<select id="count" resultType="java.lang.Long"> SELECT COUNT(1) AS total <include refid="TRACK_ACTIVE_SAFETY_PICTURE_PAGE_FROM_WITH_FUNCTION"/> </select> <sql id="TRACK_ACTIVE_SAFETY_PICTURE_PAGE_FROM_WITH_FUNCTION"> FROM test WHERE id = #{param} </sql>