以下为自己整理出来的mybatis常用标签和方法,仅作参考
1.namespace
<mapper namespace="com.example.demo.mapper.SystemMapper.CompanyMapper" ></mapper>
namespace:指向对应的Mapper的接口java文件
2.resultMap
<resultMap id="BaseResultMap" type="com.example.demo.model.SystemModel.UserModel">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="INTEGER" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="company_id" property="companyId" jdbcType="INTEGER"/>
<result column="department_id" property="departmentId" jdbcType="INTEGER"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
<association property="company" javaType="com.example.demo.entity.SystemEntity.Company" >
<id column="companyId" property="id" jdbcType="INTEGER"/>
<result column="companyName" property="name" jdbcType="VARCHAR"/>
</association>
<association property="department" javaType="com.example.demo.entity.SystemEntity.Department" >
<id column="departmentId" property="id" jdbcType="INTEGER"/>
<result column="departmentName" property="name" jdbcType="VARCHAR"/>
</association>
<collection property="roleList" javaType="java.util.List" ofType="com.example.demo.entity.SystemEntity.Role">
<id column="roleId" property="id" jdbcType="INTEGER"/>
<result column="roleName" property="name" jdbcType="VARCHAR"/>
<result column="roleDescription" property="description" jdbcType="LONGVARCHAR"/>
</collection>
</resultMap>
id:指向表的id
result:指向表的其他属性
association:进行一对一的属性的映射
collection:进行一对多的属性的映射
3.collection ----主查询嵌套子查询
//以下主要用于PageHelper插件的分页使用,用于解决PageHelper分页问题
//collection需要进行主查询嵌套子查询
<resultMap id="ResultMap" type="com.example.demo.model.SystemModel.CompanyModel" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="contacts" property="contacts" jdbcType="VARCHAR" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
//进行嵌套子查询,将需要的参数映射到column中
<collection property="departmentList" javaType="java.util.List" ofType="com.example.demo.entity.SystemEntity.Department" column="id" select="queryTemplateById">
</collection>
</resultMap>
<resultMap id="department" type="com.example.demo.entity.SystemEntity.Department">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="company_id" property="companyId" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
</resultMap>
<!--parent_id还未增加映射上去-->
//利用上面传递的column进行子查询
<select id="queryTemplateById" parameterType="java.lang.Integer" resultMap="department">
select id,name,company_id
from department_info
where company_id = #{id}
</select>
<select id="queryByPage" resultMap="ResultMap">
select c.*
from company_info c
</select>
<select id="queryByPageAndCondition" parameterType="java.lang.String" resultMap="ResultMap">
select c.*
from company_info c
where c.name like '%${value}%'
</select>
4.useGeneratedKeys--获取插入时主键id的值
<insert id="insertCompany" parameterType="com.example.demo.model.SystemModel.CompanyModel" useGeneratedKeys="true" keyProperty="id">
insert into company_info(username,password)
value(#{username},#{password})
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
5.foreach ---利用foreach进行迭代
在mybatis的mapper配置文件中,可以利用<foreach>标签实现sql条件的循环,可完成类似批量的sql
mybatis接受的参数分为:(1)基本类型(2)对象(3)List(4)数组(5)Map
无论传哪种参数给mybatis,他都会将参数放在一个Map中:
如果传入基本类型:变量名作为key,变量值作为value 此时生成的map只有一个元素。
如果传入对象: 对象的属性名作为key,属性值作为value
如果传入List: “list”作为key,这个List是value (这类参数可以迭代,利用<foreach>标签实现循环)
如果传入数组: “array”作为key,数组作为value(同上)
如果传入Map: 键值不变。
<foreach>标签的用法:
collection:要循环的集合
index:循环索引(不知道啥用。。)
item:集合中的一个元素(item和collection,按foreach循环理解)
open:以什么开始
close:以什么结束
separator:循环内容之间以什么分隔
<delete id="deleteCompany" parameterType="java.util.List">
delete
from company_info
where id in
<foreach collection="list" item="item" separator="," open="(" close=")" index="index">
#{item}
</foreach>
</delete>
6.map键值对的传参---@Param("userId") ====== #{userId}
*Mapper.java中
int insertUserRoleRelation(@Param("userId") Integer userId, @Param("roleId") Integer roleId);
*Mapper.xml
<!--新增中间表user_role_info的数据-->
<insert id="insertUserRoleRelation" parameterType="map">
insert
into user_role_info(user_id,role_id)
value (#{userId},#{roleId})
</insert>
7.sql片段使用
mybatis动态SQL中的sql片段
在mybatis中通过使用SQL片段可以提高代码的重用性,如下情景:
1、创建动态SQL
<sql id="sql_count">select count(*)</sql>
2、使用
<select id="selectListCountByParam" parameterType="map" resultType="String">
<include refid="sql_count"/> from table_name
</select>
3、解析
在使用sql片段时使用include标签通过sql片段的id进行引用,sql片段的ID在当前空间必须为唯一的
当然,sql片段中也可以写其他的内容,只要符合语法规范都是可以的。如下:
<sql id="sql_where">
<trim prefix="WHERE" prefixoverride="AND | OR">
<if test="id != null">AND id=#{id}</if>
<if test="name != null and name.length()>0">AND name=#{name}</if>
<if test="gender != null and gender.length()>0">AND gender=#{gender}</if>
</trim>
</sql>
<select id="updateByKey" parameterType="Map" resultType="List">
select * from user
<include refid="sql_where">
</select>
8.set标签使用
mybatis动态SQL中的set标签的使用
set标记是mybatis提供的一个智能标记,我一般将其用在修改的sql中,例如以下情况:
<update>
update user
<set>
<if test="name != null and name.length()>0">name = #{name},</if>
<if test="gender != null and gender.length()>0">gender = #{gender},</if>
</set>
where id = #{id}
</update>
在上述的代码片段当中,假如说现在三个字段都有值得话,那么上面打印的SQL语句如下:
update user set name='xxx' , gender='xx' where id='x'
在上面标红的地方是没有逗号的,也就是说set标记已经自动帮助我们把最后一个逗号给去掉了
9.where标签的使用
mybatis动态sql中where标签的使用
where标记的作用类似于动态sql中的set标记,他的作用主要是用来简化sql语句中where条件判断的书写的,如下所示:
<select id="selectByParams" parameterType="map" resultType="user">
select * from user
<where>
<if test="id != null ">id=#{id}</if>
<if test="name != null and name.length()>0" >and name=#{name}</if>
<if test="gender != null and gender.length()>0">and gender = #{gender}</if>
</where>
</select>
在上述SQL中加入ID的值为null的话,那么打印出来的SQL为:select * from user where name="xx" and gender="xx"
where 标记会自动将其后第一个条件的and或者是or给忽略掉
10.trim标签的使用
以下操作会出现多出逗号,的错误
则使用trim标签则有方法可以去除
suffixOverrides="," 表示去除sql语句结尾多余的逗号.
<trim prefix="where" prefixOverrides="or">
<if test="condition != null and condition != '' ">
or u.name like '%${condition}%'
or c.name like '%${condition}%'
</if>
</trim>
11.choose (when, otherwise)标签
choose (when, otherwise)标签
有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件。MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。
choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
例如下面例子,同样把所有可以限制的条件都写上,方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑,我们使用where将choose包起来,放置关键字多于错误。
<!-- choose(判断参数) - 按顺序将实体类 User 第一个不为空的属性作为:where条件 -->
<select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">
SELECT *
FROM User u
<where>
<choose>
<when test="username !=null ">
u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')
</when >
<when test="sex != null and sex != '' ">
AND u.sex = #{sex, jdbcType=INTEGER}
</when >
<when test="birthday != null ">
AND u.birthday = #{birthday, jdbcType=DATE}
</when >
<otherwise>
</otherwise>
</choose>
</where>
</select>
choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中 的 choose 很类似。
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
and content = #{content}
</when>
<otherwise>
and owner = "owner1"
</otherwise>
</choose>
</select>
when元素表示当 when 中的条件满足的时候就输出其中的内容,跟 JAVA 中的 switch 效果差不多的是按照条件的顺序,当 when 中有条件满足的时候,就会跳出 choose,即所有的 when 和 otherwise 条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出 otherwise 中的内容。所以上述语句的意思非常简单, 当 title!=null 的时候就输出 and titlte = #{title},不再往下判断条件,当title为空且 content!=null 的时候就输出 and content = #{content},当所有条件都不满足的时候就输出 otherwise 中的内容
12.Mybatis.xml中大于等于小于等于的写法
第一种写法(1):
原符号 < <= > >= & ' "
替换符号 < <= > >= & ' "
例如:sql如下:
create_date_time >= #{startTime} and create_date_time <= #{endTime}
第二种写法(2):
大于等于
<![CDATA[ >= ]]>
小于等于
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and create_date_time <![CDATA[ <= ]]> #{endTime}
Mybatis.xml文件中大于小于等于
第一种写法:
原符号 < <= > >= & ' "
替换符号 < <= > >= & ' "
例如:sql如下:
create_date_time >= #{startTime} and create_date_time <= #{endTime}
第二种写法:
大于等于
<![CDATA[ >= ]]>
小于等于
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and create_date_time <![CDATA[ <= ]]> #{endTime}