没有试验过本篇中的内容
参数:
通常情况下,Mybatis的mapper文件中Select、Inser、Update和Delete只接收一个参数,并用parameterType指定。
要指定多个参数,可以将多个参数加入到一个hashmap,然后将hashmap作为参数传入。
另外的方法是使用@Param注解标注多个参数,例如:
- List<Contact> selectQuery(@Param(value="contact") Contact contact,@Param(value="start") int start,@Param("size") int size);
- <select id="selectQuery" resultType="Contact">
- select * from contacts
- <where>
- <if test="contact.name!=null">
- name like concat('%',#{contact.name},'%')
- </if>
- <if test="contact.email!=null">
- and email like concat('%',#{contact.email},'%')
- </if>
- </where>
- limit #{start},#{size}
- </select>
条件:
if:条件判断
官方文档代码片段:
- <select id="findActiveBlogWithTitleLike" parameterType="Blog"
- resultType="Blog">
- SELECT * FROM BLOG
- WHERE state = ‘ACTIVE’
- <if test="title != null">
- AND title like #{title}
- </if>
- </select>
choose:多个条件判断,包含when otherwise
官方文档代码片段:
- <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">
- SELECT * FROM BLOG WHERE state = ‘ACTIVE’
- <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>
- </select>
where:构造where条件片段
官方文档代码片段:
- <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">
- SELECT * FROM BLOG
- <where>
- <if test="state != null">
- state = #{state}
- </if>
- <if test="title != null">
- AND title like #{title}
- </if>
- <if test="author != null and author.name != null">
- AND author_name like #{author.name}
- </if>
- </where>
- </select>
日志:
启动单个mapper的日志
log4j.logger.com.mybatistest.mapper.ContactMapper=TRACE
启动一组mapper的日志
log4j.logger.com.mybatistest.mapper=TRACE
启动日志后,能看到运行的SQL和参数。