mybatis常用标签有:
select,delete,insert,update分别对应增加、删除、修改,查找;
sql :“定义”一段sql语句,需要的时候再引用;
set:在update标签内部使用,相当于sql语句里的“set”;
where:相当于sql语句里的“set”;
parameterMap, resultMap:定义参数或返回结果的数据类型;
if:用于判断;
下面给出几个例子,基本包括了各种标签的常用用法;
1. 查询
id属性要与接口里的方法名一致
如果需要传参,有两种方法配置:parameterType指定类型,若参数为基本数据类型,直接写类型名,如int,string等,若参数不止一个,则要把参数封装,封装成map或者类,写上类的全路径;parameterMap指定类型,写上parameterMap的id
where, if标签用法:
<where>
<if test="这里写判断条件"> 这里写sql语句,可以是参数(如and GENDER = #{gender}),如果多个判断语句,第一个and会被mybatis自动删除,所以不用担心</if>
<if test="name != null and !"".equals(name.trim())">
and NAME like '%' #{name} '%'</if>
</where>
注意:传进来的参数用#{参数}表示;if条件里逻辑运算与、或分别对应and,or,不能使用&&,||;双引号要用";表示。
sql标签用法:
<sql id="cols">ID, NAME, GENDER ,AGE</sql>
在需要的时候使用include标签引用,refid写上sql标签的id。
完整的select语句如下:
<select id="queryUserList" parameterType="bean.User" resultType="bean.User">
select <include refid="cols"/> from user
<where>
<if test="gender != null and !"".equals(gender.trim())">
and GENDER = #{gender}</if>
<if test="name != null and !"".equals(name.trim())">
and NAME like '%' #{name} '%'</if>
</where>
order by ID
</select>
- 删除
只有一个参数时,一般写#{_parameter},but,其实#{}里面写啥都可以~
<delete id="deleteOne" parameterType="int">
delete from t_category where id=#{_parameter}
</delete>
- 单条插入
<insert id="insertOne" parameterType="bbs.pojo.Category">
insert into t_category(name,description) values(#{name},#{description})
</insert>
- 批量插入
这里顺便介绍了foreach标签,和jstl的foreach标签很相似,注意separator标签别掉了。
比如SQL语句insert into t_category(name,description) values(’a’,’aa’),(‘b’,’bbb’)
<insert id="insertBatch" parameterType="java.util.List">
insert into t_category(name,description) values
<foreach collection="list" item="e" separator=",">
(#{e.name},#{e.description})
</foreach>
</insert>
- 修改
使用set标签。其他的都一样的
<update id="update" parameterType="bbs.pojo.Category">
update t_category
<set>
<if test="name != null and !"".equals(name.trim())">
name=#{name},
</if>
<if test="description != null and !"".equals(description.trim())">
description=#{description}
</if>
</set>
where id=#{id}
</update>
- resultMap标签
type属性写上类的全路径名;id子标签与数据库表的主键对应,id子标签的column属性是列名称,在sql语句里使用时要与此处名称一致,jdbcType属性配置类型,property属性要与实体类的属性名一致;result子标签属性和id标签的属性相同
<resultMap type="bean.CommandContent" id="Content">
<id column="ID" jdbcType="INTEGER" property="id" />
<result column="CONTENT" jdbcType="VARCHAR" property="content" />
<result column="COMMAND_ID" jdbcType="VARCHAR" property="command_id" />
</resultMap>
- typeAlias标签