Mybatis中各种操作总结
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));尤其需要注意;
4.当传参比较多,各种类型都有时
Dao层代码
List<Integer> getTodaySuccessList(@Param("vehiclestr") List<Integer> vehiclestr, @Param("btime") String btime, @Param("etime") String etime);
xml文件代码:
<select id="getTodaySuccessList" resultType="java.lang.Integer">
SELECT
v.Status
FROM videodownload v
WHERE
v.VehicleId IN
<foreach collection="vehiclestr" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
AND v.CreatedTime <![CDATA[ >= ]]> #{btime}
AND v.CreatedTime <![CDATA[ <= ]]> #{etime}
</select>
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>