MyBatis动态标签

常见的动态标签

  1. if

  2. choose, when, otherwise

  3. trim,where,set

  4. foreach

  5. bind

  6. sql

    mybatis通过OGNL表达式来进行取值操作;比如:#{username}

Mybatis两个内置参数

  1. _parameter: 如果接口传入多个参数,这些参数都包含在这一个参数中,如果传入一个,那该参数就代表传来的参数

  2. _databaseId: 如果在mybatis核心配置文件中配置了databaseIdProvider(数据库厂商)标签,则该参数代表当前数据库厂商别名
    这两个参数可以搭配if标签来使用,

    <if text="_databaseId == 'mysql'">
        SELECT * FROM user
    	<if text="_parameter != null">
        	WHERE username = #{_parameter.属性名}
        if>
    if>
    

1. if使用


<if test="title != null">
    AND title like #{title}
if>

2. choose使用


<choose>
    
    <when test="title != null">
        AND title like #{title}
    when>
    <when test="author != null and author.name != null">
        AND author_name like #{author.name}
    when>
    <otherwise>
        AND featured = 1
    otherwise>
choose>

3. trim使用



<trim prefix="WHERE" prefixOverrides="AND | OR" suffix="" suffixOverrides="">
  ...
trim>

4. set使用


<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},if>
      <if test="password != null">password=#{password},if>
      <if test="email != null">email=#{email},if>
      <if test="bio != null">bio=#{bio}if>
    set>
  where id=#{id}
update>

5. foreach使用



<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
  foreach>
select>

<insert id="insertTest">
	INSERT INTO user_tbl(id,name)
    VALUES
    <foreach collection="userList" item="user" separator=",">
    	(#{user.id}, #{user.name})
    foreach>
insert>

6. bind使用


<select id="selectBlogsLike" resultType="Blog">
  <bind name="likename" value="'%' + #{username} + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{likename}
select>

7. sql使用



<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password sql>
<select id="selectUsers" resultType="map">
  select
    <include refid="userColumns"><property name="alias" value="t1"/>include>,
    <include refid="userColumns"><property name="alias" value="t2"/>include>
  from some_table t1
    cross join some_table t2
select>

你可能感兴趣的:(笔记,数据库,java,database)