1、<foreach></foreach>的运用
1.1、根据list循环
<select id="selectUserByUserIds" resultType="com.sys.pojo.po.User">
select *
from sys_user
where user_id in
<foreach collection="list" item="entity" separator="," open="(" close=")">
#{entity}
</foreach>
</select>
<!--
User selectUserByUserIds(List<String> list);
-->
1.2、根据字符串用逗号分隔循环
<select id="selectUserByUserIds" resultType="com.sys.pojo.po.User">
select *
from sys_user
where user_id in
<foreach item="item" index="index" collection="ids.split(',')" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- ids为入参
User selectUserByUserIds(String ids);
-->
1.3、表数据的批量插入
<insert id="insertBatch" parameterType="com.sys.pojo.po.User">
insert into sys_user(user_id, username, password, create_time)
values
<trim suffixOverrides="," >
<foreach collection="list" item="entity">
(#{entity.userId}, #{entity.username}, #{entity.password}, #{entity.createTime}),
</foreach>
</trim>
</insert>
<!--
int insertBatch(List<User> list);
-->
<!--
获取自动增加的id
useGeneratedKeys="true" keyColumn="element_id" keyProperty="elementId"
-->
2、模糊查询
<!-- 左匹配模糊查询-->
<select id="selectUserByUsername" resultType="com.sys.pojo.po.User">
select *
from sys_user
where username like concat(#{username},'%')
</select>
<!--
User selectUserByUsername(String username);
-->
3、‘<’冲突
<select id="selectUserByTime" resultType="com.sys.pojo.po.User">
select *
from sys_user
<where>
<!-- 小于(两种写法) -->
<![CDATA[AND create_time <= #{createTime}]]>
AND create_time <= #{createTime}
<!-- 大于(两种写法) -->
<![CDATA[AND create_time >= #{createTime}]]>
AND create_time >= #{createTime}
</where>
</select>
<!--
User selectUserByTime(Date createTime);
-->
4、#{}与${}的区别
<!-- ids = "19,20,21" id为自增id-->
<delete id="deleteUserByUserIds">
delete sys_user from id in (#{ids})
</delete>
<!--
int deleteUserByUserIds(String ids);
delete sys_user from id in ('19,20,21'),匹配了id为19的记录并删除了该记录,无法匹配其他数据
-->
<delete id="deleteUserByUserIds">
delete sys_user from id in (${ids})
</delete>
<!--
int deleteUserByUserIds(String ids);
delete sys_user from id in (19,20,21),19,20,21三条记录均被删除成功
-->
<!--
注:#{}对字符串类型会自动加单引号,而${}不会
-->
5、xml文件里resultMap使用
5.1 查询list信息
<resultMap id="BaseResultMap" type="com.sys.pojo.po.User">
<id column="ID" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<collection property="roleList" javaType="list" ofType="com.sys.pojo.po.Role"
select="findRole" column="ID">
</collection>
</resultMap>
<select id="findNodes" resultType="com.sys.pojo.po.Role">
SELECT
t.ID,
t.role_code,
t.role_name
FROM
role t
where t.id= #{eventFlowId,jdbcType=INTEGER}
</select>