一、MyBatis的mapper映射文件中的一些常用标签
mapper
:根元素,包含namespace属性,指定命名空间。
在映射器XML文件中使用`<mapper>`标签定义命名空间和其他映射规则。
一个简单的`<mapper>`标签的使用示例如下:
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUser" parameterType="int" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
foreach
:<foreach>
标签的主要属性有:
- collection:要遍历的集合名,可以是List、Set或者数组。
- item:循环过程中每个元素自定义的别名。
- open:循环开始前要添加的字符串,比如"("。
- close:循环结束后要添加的字符串,比如")"。
- separator:每个元素也就是item之间的分隔符,比如","。
# 一般foreach结合 多条件判断 IN 或者 添加多个对象使用
WHERE id IN
<foreach item="userId" collection="list" open="(" separator="," close=")">
#{userId}
</foreach>
if
:判断条件。其中主要属性为 item,也就是指所需字段的条件表达式,结果为true 和 false
# 一般多用于 更新时 set 多字段判空 和 多条件查询 where 多字段判空
<where>
#当username 字段不为空才执行 where条件判断
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
resultMap
:定义结果映射规则,包括<id>
、<result>
、<association>
、<collection>
等子元素。
<resultMap id="userResultMap" type="User">
# 将数据库中的user_id字段名映射成 id ,为了方便 User对象中的属性id 映射获取 user_id
# 与在查询时 取别名 用 as 作用类似 但resultMap 映射方便复用
<id property="id" column="user_id" />
<result property="username" column="username" />
<result property="email" column="email" />
</resultMap>
<select id="selectUser" resultMap="userResultMap">
SELECT user_id, username, email
FROM users
WHERE id = #{id}
</select>
sql
:通过<sql>
标签定义的SQL可以在其他查询中通过<include>
标签复用。
#定义需要复用的代码
<sql id="selectUserColumns">
id, username, email, password
</sql>
<select id="selectUserById" resultType="User">
SELECT
#利用include标签调用复用代码
<include refid="selectUserColumns" />
FROM users
WHERE id = #{id}
</select>
以下简单的一些语句执行标签:
<where>
:方便用于多字段的条件判断和判空。
insert
:映射插入操作的SQL语句。
update
:映射更新操作的SQL语句。
delete
:映射删除操作的SQL语句。
select
:映射查询操作的SQL语句。