Mybatis SQL参数、条件、日志

来源:互联网 发布:深度卷积网络进展 编辑:程序博客网 时间:2024/06/11 14:48

没有试验过本篇中的内容

 

参数:

通常情况下,Mybatis的mapper文件中Select、Inser、Update和Delete只接收一个参数,并用parameterType指定。

要指定多个参数,可以将多个参数加入到一个hashmap,然后将hashmap作为参数传入。

另外的方法是使用@Param注解标注多个参数,例如:

[java] view plaincopy
  1. List<Contact> selectQuery(@Param(value="contact") Contact contact,@Param(value="start"int start,@Param("size"int size);  
其中参数contact类型为Contact,mapper对于的xml配置为:

[html] view plaincopy
  1. <select id="selectQuery" resultType="Contact">  
  2.         select * from contacts   
  3.         <where>  
  4.             <if test="contact.name!=null">  
  5.                 name like concat('%',#{contact.name},'%')  
  6.             </if>  
  7.             <if test="contact.email!=null">  
  8.                 and email like concat('%',#{contact.email},'%')  
  9.             </if>  
  10.         </where>  
  11.         limit #{start},#{size}  
  12.     </select>  
因为多个参数的存在,引用name属性必须指定contact.name。

条件:

if:条件判断

官方文档代码片段:

[html] view plaincopy
  1. <select id="findActiveBlogWithTitleLike" parameterType="Blog"  
  2.         resultType="Blog">  
  3.     SELECT * FROM BLOG  
  4.     WHERE state = ‘ACTIVE’  
  5.     <if test="title != null">  
  6.         AND title like #{title}  
  7.     </if>  
  8. </select>  

choose:多个条件判断,包含when otherwise

官方文档代码片段:

[html] view plaincopy
  1. <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">  
  2.     SELECT * FROM BLOG WHERE state = ‘ACTIVE’  
  3.     <choose>  
  4.         <when test="title != null">  
  5.             AND title like #{title}  
  6.         </when>  
  7.         <when test="author != null and author.name != null">  
  8.             AND author_name like #{author.name}  
  9.         </when>  
  10.         <otherwise>  
  11.             AND featured = 1  
  12.         </otherwise>  
  13.     </choose>  
  14. </select>  

where:构造where条件片段

官方文档代码片段:

[html] view plaincopy
  1. <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">  
  2.     SELECT * FROM BLOG  
  3.     <where>  
  4.         <if test="state != null">  
  5.             state = #{state}  
  6.         </if>  
  7.         <if test="title != null">  
  8.             AND title like #{title}  
  9.         </if>  
  10.         <if test="author != null and author.name != null">  
  11.             AND author_name like #{author.name}  
  12.         </if>  
  13.     </where>  
  14. </select>  
会这3个基本上就好了。。


日志:

启动单个mapper的日志

log4j.logger.com.mybatistest.mapper.ContactMapper=TRACE

启动一组mapper的日志

log4j.logger.com.mybatistest.mapper=TRACE

启动日志后,能看到运行的SQL和参数。

原创粉丝点击