由于select只接受一个附加参数,所以需要封装后传入,动态拼接使用了ognl表达式,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <select id="queryData" parameter="com.imooc.bean.Message" resultMap="">
select ID,COMMAND from MESSAGE where 1=1
<!--
这里"是转义的上引号 &不能在这里用所以用ognl自带的操作符and 还有or 、in、 not in
ognl可以直接获取对象中的属性值,这里的command是从Message中获得,还能调用对象属性
-->
<if test="command!=null and !&quit;".equals(command.trim())">
<!--这里下面的语法并不是ognl表达式,是mybatis自己的-->
and COMMAND=#{command}
</if>
<if test="description!=null and !&quit;".equals(command.trim())">
and description like '%' #{description} '%'
</if>
</select>
|
## 使用log4j调试动态SQL 引用相应jar(log4j-*.jar)和configuration.xml 输出分为几个级别
log.debug() log.info() log.warn() log.error()在log4j.properties中配置 log4j.rootLogger=DEBUG,Console如果是以上配置则会输出所有,输出为大于配置等级的信息,如果配了ERROR则只会输出log.error()
其中Console只是取的一个变量名,可以更改,但是前面的不能更改
1 2 3 4 5 6 7 8 | log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
//定义输出布局
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
//定义输出格式 %d日期 %t线程 -5表示输出至少为5为不足则补齐 %p输出日志级别 %c输出日志是所属类全名 %m输出时附加的信息 %n换行
log4j.appender.Console.layout.ConversionPattern=%d[%t]%-5p[%c]-%m%n
//org.apache是自己写的包名,个性化 第一行是整个工程的
log4j.logger.org.apache=INFO
|
mybatis本身定义了调用log工具的借口,导入哪种jar就用哪种日志,org.apache.ibatis.logging下源码。
MyBatis中的配置文件标签
foreach标签
1 2 3 4 5 6 7 8 9 10 | ```xml
<delete id="deleteBatch" parameterType="java.util.List">
delete from message where id in(
<!--用separator让mybatis来拼接,值为所需分隔符,这里index没有使用单纯只是做笔记-->
<foreach collection="list" index="i" item="item" separator=",">
#{item}
</foreach>
)
</delete>
```
|
## where标签
1 2 3 4 5 6 7 8 | <select id="queryData" parameter="com.imooc.bean.Message" resultMap="">
select ID,COMMAND from MESSAGE
<where>
<if test="command!=null and !&quit;".equals(command.trim())">
and COMMAND=#{command}
</if>
</where>
</select>
|
## sql标签
可以重复引用sql片段。
1 2 3 4 5 6 7 8 9 10 | <select id="queryData" parameter="com.imooc.bean.Message" resultMap="">
select <include refid="colums"/> from MESSAGE
<where>
<if test="command!=null and !&quit;".equals(command.trim())">
and COMMAND=#{command}
</if>
</where>
</select>
<sql id="colums"> ID,COMMADN</sql>
|
## set标签 主要解决拼接时分隔符
1 2 3 4 5 6 7 8 | <update id="">
update message
<set>
<if test="command!=null and !&quit;".equals(command.trim())">
and COMMAND=#{command}
</if>
</set>
</update>
|
## trim标签 可以代替where和set
1 2 3 | <!--prefix 如果内有内容加入where suffix如果有内容输出则加上 如果有会在最后切掉prefixOverrides="and/or" suffixOverrides=","-->
<trim prefix="where">
</trim>
|
## choose标签
类似java的switch case
1 2 3 4 5 6 7 8 9 | <choose>
<when test="">
</when>
<when test="">
</when>
<when test="">
</when>
<otherwise></otherwise>
</choose>
|
## association用于一对一映射
1 | <association property="" resultMap="sss.resultid"/>
|
原文:大专栏 Mybatis动态sql拼接以及使用log4j