ibatis常用sql
(1) 输入参数为单个值
- <delete id="com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore"
- parameterClass="long">
- delete from
- MemberAccessLog
- where
- accessTimestamp = #value#
- </delete>
<delete id="com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore"
parameterClass="long">
delete from
MemberAccessLog
where
accessTimestamp = #value#
</delete>
(2) 输入参数为一个对象
- <insert id="com.fashionfree.stat.accesslog.MemberAccessLog.insert"
- parameterClass="com.fashionfree.stat.accesslog.model.MemberAccessLog>
- insert into MemberAccessLog
- (
- accessLogId, memberId, clientIP,
- httpMethod, actionId, requestURL,
- accessTimestamp, extend1, extend2,
- extend3
- )
- values
- (
- #accessLogId#, #memberId#,
- #clientIP#, #httpMethod#,
- #actionId#, #requestURL#,
- #accessTimestamp#, #extend1#,
- #extend2#, #extend3#
- )
- </insert>
<insert id="com.fashionfree.stat.accesslog.MemberAccessLog.insert"
parameterClass="com.fashionfree.stat.accesslog.model.MemberAccessLog>
insert into MemberAccessLog
(
accessLogId, memberId, clientIP,
httpMethod, actionId, requestURL,
accessTimestamp, extend1, extend2,
extend3
)
values
(
#accessLogId#, #memberId#,
#clientIP#, #httpMethod#,
#actionId#, #requestURL#,
#accessTimestamp#, #extend1#,
#extend2#, #extend3#
)
</insert>
(3) 输入参数为一个java.util.HashMap
- <select id="com.fashionfree.stat.accesslog.selectActionIdAndActionNumber"
- parameterClass="hashMap"
- resultMap="getActionIdAndActionNumber">
- select
- actionId, count(*) as count
- from
- MemberAccessLog
- where
- memberId = #memberId#
- and accessTimestamp > #start#
- and accessTimestamp <= #end#
- group by actionId
- </select>
<select id="com.fashionfree.stat.accesslog.selectActionIdAndActionNumber"
parameterClass="hashMap"
resultMap="getActionIdAndActionNumber">
select
actionId, count(*) as count
from
MemberAccessLog
where
memberId = #memberId#
and accessTimestamp > #start#
and accessTimestamp <= #end#
group by actionId
</select>
(4) 输入参数中含有数组
- <insert id="updateStatusBatch" parameterClass="hashMap">
- update
- Question
- set
- status = #status#
- <dynamic prepend="where questionId in">
- <isNotNull property="actionIds">
- <iterate property="actionIds" open="(" close=")" conjunction=",">
- #actionIds[]#
- </iterate>
- </isNotNull>
- </dynamic>
- </insert>
<insert id="updateStatusBatch" parameterClass="hashMap">
update
Question
set
status = #status#
<dynamic prepend="where questionId in">
<isNotNull property="actionIds">
<iterate property="actionIds" open="(" close=")" conjunction=",">
#actionIds[]#
</iterate>
</isNotNull>
</dynamic>
</insert>
说明:actionIds为传入的数组的名字;
使用dynamic标签避免数组为空时导致sql语句语法出错;
使用isNotNull标签避免数组为null时ibatis解析出错
(5)传递参数只含有一个数组
- <select id="com.fashionfree.stat.accesslog.model.StatMemberAction.selectActionIdsOfModule"
- resultClass="hashMap">
- select
- moduleId, actionId
- from
- StatMemberAction
- <dynamic prepend="where moduleId in">
- <iterate open="(" close=")" conjunction=",">
- #[]#
- </iterate>
- </dynamic>
- order by
- moduleId
- </select>
<select id="com.fashionfree.stat.accesslog.model.StatMemberAction.selectActionIdsOfModule"
resultClass="hashMap">
select
moduleId, actionId
from
StatMemberAction
<dynamic prepend="where moduleId in">
<iterate open="(" close=")" conjunction=",">
#[]#
</iterate>
</dynamic>
order by
moduleId
</select>
说明:注意select的标签中没有parameterClass一项
另:这里也可以把数组放进一个hashMap中,但增加额外开销,不建议使用
(6)让ibatis把参数直接解析成字符串
- <select id="com.fashionfree.stat.accesslog.selectSumDistinctCountOfAccessMemberNum"
- parameterClass="hashMap" resultClass="int">
- select
- count(distinct memberId)
- from
- MemberAccessLog
- where
- accessTimestamp >= #start#
- and accessTimestamp < #end#
- and actionId in $actionIdString$
- </select>
<select id="com.fashionfree.stat.accesslog.selectSumDistinctCountOfAccessMemberNum"
parameterClass="hashMap" resultClass="int">
select
count(distinct memberId)
from
MemberAccessLog
where
accessTimestamp >= #start#
and accessTimestamp < #end#
and actionId in $actionIdString$
</select>
说明:使用这种方法存在sql注入的风险,不推荐使用
(7)分页查询 (pagedQuery)
- <select id="com.fashionfree.stat.accesslog.selectMemberAccessLogBy"
- parameterClass="hashMap" resultMap="MemberAccessLogMap">
- <include refid="selectAllSql"/>
- <include refid="whereSql"/>
- <include refid="pageSql"/>
- </select>
- <select id="com.fashionfree.stat.accesslog.selectMemberAccessLogBy.Count"
- parameterClass="hashMap" resultClass="int">
- <include refid="countSql"/>
- <include refid="whereSql"/>
- </select>
- <sql id="selectAllSql">
- select
- accessLogId, memberId, clientIP,
- httpMethod, actionId, requestURL,
- accessTimestamp, extend1, extend2,
- extend3
- from
- MemberAccessLog
- </sql>
- <sql id="whereSql">
- accessTimestamp <= #accessTimestamp#
- </sql>
- <sql id="countSql">
- select
- count(*)
- from
- MemberAccessLog
- </sql>
- <sql id="pageSql">
- <dynamic>
- <isNotNull property="startIndex">
- <isNotNull property="pageSize">
- limit #startIndex# , #pageSize#
- </isNotNull>
- </isNotNull>
- </dynamic>
- </sql>
<select id="com.fashionfree.stat.accesslog.selectMemberAccessLogBy"
parameterClass="hashMap" resultMap="MemberAccessLogMap">
<include refid="selectAllSql"/>
<include refid="whereSql"/>
<include refid="pageSql"/>
</select>
<select id="com.fashionfree.stat.accesslog.selectMemberAccessLogBy.Count"
parameterClass="hashMap" resultClass="int">
<include refid="countSql"/>
<include refid="whereSql"/>
</select>
<sql id="selectAllSql">
select
accessLogId, memberId, clientIP,
httpMethod, actionId, requestURL,
accessTimestamp, extend1, extend2,
extend3
from
MemberAccessLog
</sql>
<sql id="whereSql">
accessTimestamp <= #accessTimestamp#
</sql>
<sql id="countSql">
select
count(*)
from
MemberAccessLog
</sql>
<sql id="pageSql">
<dynamic>
<isNotNull property="startIndex">
<isNotNull property="pageSize">
limit #startIndex# , #pageSize#
</isNotNull>
</isNotNull>
</dynamic>
</sql>
说明:本例中,代码应为:
HashMap hashMap = new HashMap();
hashMap.put(“accessTimestamp”, someValue);
pagedQuery(“com.fashionfree.stat.accesslog.selectMemberAccessLogBy”, hashMap);
pagedQuery方法首先去查找名为com.fashionfree.stat.accesslog.selectMemberAccessLogBy.Count 的mapped statement来进行sql查询,从而得到com.fashionfree.stat.accesslog.selectMemberAccessLogBy查询的记录个数,
再进行所需的paged sql查询(com.fashionfree.stat.accesslog.selectMemberAccessLogBy),具体过程参见utils类中的相关代码
(8)sql语句中含有大于号>、小于号<
1. 将大于号、小于号写为: > < 如:
- <delete id="com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore" parameterClass="long">
- delete from
- MemberAccessLog
- where
- accessTimestamp <= #value#
- </delete>
<delete id="com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore" parameterClass="long">
delete from
MemberAccessLog
where
accessTimestamp <= #value#
</delete>
2. 将特殊字符放在xml的CDATA区内:
- <delete id="com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore" parameterClass="long">
- <![CDATA[
- delete from
- MemberAccessLog
- where
- accessTimestamp <= #value#
- ]]>
- </delete>
<delete id="com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore" parameterClass="long">
<![CDATA[
delete from
MemberAccessLog
where
accessTimestamp <= #value#
]]>
</delete>
推荐使用第一种方式,写为< 和 > (XML不对CDATA里的内容进行解析,因此如果CDATA中含有dynamic标签,将不起作用)
(9)include和sql标签
将常用的sql语句整理在一起,便于共用:
- <sql id="selectBasicSql">
- select
- samplingTimestamp,onlineNum,year,
- month,week,day,hour
- from
- OnlineMemberNum
- </sql>
- <sql id="whereSqlBefore">
- where samplingTimestamp <= #samplingTimestamp#
- </sql>
- <select id="com.fashionfree.accesslog.selectOnlineMemberNumsBeforeSamplingTimestamp" parameterClass="hashmap" resultClass="OnlineMemberNum">
- <include refid="selectBasicSql" />
- <include refid="whereSqlBefore" />
- </select>
<sql id="selectBasicSql">
select
samplingTimestamp,onlineNum,year,
month,week,day,hour
from
OnlineMemberNum
</sql>
<sql id="whereSqlBefore">
where samplingTimestamp <= #samplingTimestamp#
</sql>
<select id="com.fashionfree.accesslog.selectOnlineMemberNumsBeforeSamplingTimestamp" parameterClass="hashmap" resultClass="OnlineMemberNum">
<include refid="selectBasicSql" />
<include refid="whereSqlBefore" />
</select>
注意:sql标签只能用于被引用,不能当作mapped statement。如上例中有名为selectBasicSql的sql元素,试图使用其作为sql语句执行是错误的:
sqlMapClient.queryForList(“selectBasicSql”); ×
(10)随机选取记录
- <sql id=”randomSql”>
- ORDER BY rand() LIMIT #number#
- </sql>
<sql id=”randomSql”>
ORDER BY rand() LIMIT #number#
</sql>
从数据库中随机选取number条记录(只适用于MySQL)
(11)将SQL GROUP BY分组中的字段拼接
- <sql id=”selectGroupBy>
- SELECT
- a.answererCategoryId, a.answererId, a.answererName,
- a.questionCategoryId, a.score, a.answeredNum,
- a.correctNum, a.answerSeconds, a.createdTimestamp,
- a.lastQuestionApprovedTimestamp, a.lastModified, GROUP_CONCAT(q.categoryName) as categoryName
- FROM
- AnswererCategory a, QuestionCategory q
- WHERE a.questionCategoryId = q.questionCategoryId
- GROUP BY a.answererId
- ORDER BY a.answererCategoryId
- </sql>
<sql id=”selectGroupBy>
SELECT
a.answererCategoryId, a.answererId, a.answererName,
a.questionCategoryId, a.score, a.answeredNum,
a.correctNum, a.answerSeconds, a.createdTimestamp,
a.lastQuestionApprovedTimestamp, a.lastModified, GROUP_CONCAT(q.categoryName) as categoryName
FROM
AnswererCategory a, QuestionCategory q
WHERE a.questionCategoryId = q.questionCategoryId
GROUP BY a.answererId
ORDER BY a.answererCategoryId
</sql>
注:SQL中使用了MySQL的GROUP_CONCAT函数
(12) 按照IN里面的顺序进行排序
①MySQL:
- <sql id=”groupByInArea”>
- select
- moduleId, moduleName,
- status, lastModifierId, lastModifiedName,
- lastModified
- from
- StatModule
- where
- moduleId in (3, 5, 1)
- order by
- instr(',3,5,1,' , ','+ltrim(moduleId)+',')
- </sql>
<sql id=”groupByInArea”>
select
moduleId, moduleName,
status, lastModifierId, lastModifiedName,
lastModified
from
StatModule
where
moduleId in (3, 5, 1)
order by
instr(',3,5,1,' , ','+ltrim(moduleId)+',')
</sql>
②SQLSERVER:
- <sql id=”groupByInArea”>
- select
- moduleId, moduleName,
- status, lastModifierId, lastModifiedName,
- lastModified
- from
- StatModule
- where
- moduleId in (3, 5, 1)
- order by
- charindex(','+ltrim(moduleId)+',' , ',3,5,1,')
- </sql>
<sql id=”groupByInArea”>
select
moduleId, moduleName,
status, lastModifierId, lastModifiedName,
lastModified
from
StatModule
where
moduleId in (3, 5, 1)
order by
charindex(','+ltrim(moduleId)+',' , ',3,5,1,')
</sql>
说明:查询结果将按照moduleId在in列表中的顺序(3, 5, 1)来返回
MySQL : instr(str, substr)
SQLSERVER: charindex(substr, str)
返回字符串str 中子字符串的第一个出现位置
ltrim(str)
返回字符串str, 其引导(左面的)空格字符被删除
(13) resultMap
resultMap负责将SQL查询结果集的列值映射成Java Bean的属性值。
- <resultMap class="java.util.HashMap" id="getActionIdAndActionNumber">
- <result column="actionId" property="actionId" jdbcType="BIGINT" javaType="long"/>
- <result column="count" property="count" jdbcType="INT" javaType="int"/>
- </resultMap>
<resultMap class="java.util.HashMap" id="getActionIdAndActionNumber">
<result column="actionId" property="actionId" jdbcType="BIGINT" javaType="long"/>
<result column="count" property="count" jdbcType="INT" javaType="int"/>
</resultMap>
使用resultMap称为显式结果映射,与之对应的是resultClass(内联结果映射),使用resultClass的最大好处便是简单、方便,不需显示指定结果,由iBATIS根据反射来确定自行决定。而resultMap则可以通过指定jdbcType和javaType,提供更严格的配置认证。
(14) typeAlias
- <typeAlias alias="MemberOnlineDuration" type="com.fashionfree.stat.accesslog.model.MemberOnlineDuration" />
- <typeAlias>允许你定义别名,避免重复输入过长的名字。
<typeAlias alias="MemberOnlineDuration" type="com.fashionfree.stat.accesslog.model.MemberOnlineDuration" />
<typeAlias>允许你定义别名,避免重复输入过长的名字。
(15) remap
- <select id="testForRemap" parameterClass="hashMap" resultClass="hashMap" remapResults="true">
- select
- userId
- <isEqual property="tag" compareValue="1">
- , userName
- </isEqual>
- <isEqual property="tag" compareValue="2">
- , userPassword
- </isEqual>
- from
- UserInfo
- </select>
<select id="testForRemap" parameterClass="hashMap" resultClass="hashMap" remapResults="true">
select
userId
<isEqual property="tag" compareValue="1">
, userName
</isEqual>
<isEqual property="tag" compareValue="2">
, userPassword
</isEqual>
from
UserInfo
</select>
此例中,根据参数tag值的不同,会获得不同的结果集,如果没有remapResults="true"属性,iBatis会将第一次查询时的结果集缓存,下次再执行时(必须还是该进程中)不会再执行结果集映射,而是会使用缓存的结果集。
因此,如果上面的例子中remapResult为默认的false属性,而有一段程序这样书写:
- HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
- hashMap.put("tag", 1);
- sqlClient.queryForList("testForRemap", hashMap);
- hashMap.put("tag", 2);
- sqlClient.queryForList("testForRemap", hashMap);
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("tag", 1);
sqlClient.queryForList("testForRemap", hashMap);
hashMap.put("tag", 2);
sqlClient.queryForList("testForRemap", hashMap);
则程序会在执行最后一句的query查询时报错,原因就是iBATIS使用了第一次查询时的结果集,而前后两次的结果集是不同的:(userId, userName)和(userId, userPassword),所以导致出错。如果使用了remapResults="true"这一属性,iBATIS会在每次执行查询时都执行结果集映射,从而避免错误的发生(此时会有较大的开销)。
(16) dynamic标签的prepend
dynamic标签的prepend属性作为前缀添加到结果内容前面,当标签的结果内容为空时,prepend属性将不起作用。
当dynamic标签中存在prepend属性时,将会把其嵌套子标签的第一个prepend属性忽略。例如:
- <sql id="whereSql">
- <dynamic prepend="where ">
- <isNotNull property="userId" prepend="BOGUS">
- userId = #userId#
- </isNotNull>
- <isNotEmpty property="userName" prepend="and ">
- userName = #userName#
- </isNotEmpty>
- </dynamic>
- </sql>
<sql id="whereSql">
<dynamic prepend="where ">
<isNotNull property="userId" prepend="BOGUS">
userId = #userId#
</isNotNull>
<isNotEmpty property="userName" prepend="and ">
userName = #userName#
</isNotEmpty>
</dynamic>
</sql>
此例中,dynamic标签中含有两个子标签<isNotNull>和<isNotEmpty>。根据前面叙述的原则,如果<isNotNull>标签中没有prepend="BOGUS" 这一假的属性来让dynamic去掉的话,<isNotEmpty>标签中的and就会被忽略,会造成sql语法错误。
注意:当dynamic标签没有prepend属性时,不会自动忽略其子标签的第一个prepend属性。
ibatis常用sql的更多相关文章
- 值得注意的ibatis动态sql语法格式
一.Ibatis常用动态sql语法,简单粗暴用一例子 <select id="iBatisSelectList" parameterClass="java.util ...
- Mysql 常用 SQL 语句集锦
Mysql 常用 SQL 语句集锦 基础篇 //查询时间,友好提示 $sql = "select date_format(create_time, '%Y-%m-%d') as day fr ...
- oracle(sql)基础篇系列(一)——基础select语句、常用sql函数、组函数、分组函数
花点时间整理下sql基础,温故而知新.文章的demo来自oracle自带的dept,emp,salgrade三张表.解锁scott用户,使用scott用户登录就可以看到自带的表. #使用ora ...
- 常用SQL[ORACLE]
1.常用系统函数 2.常用sql语句 3.一些定义和关键字 4.需要注意点 1.常用系统函数 ↑ --decode decode(column,if_value,value,elseif_ ...
- Oracle常用SQL查询(2)
三.查看数据库的SQL 1 .查看表空间的名称及大小 select t.tablespace_name, round ( sum (bytes / ( 1024 * 1024 )), 0 ) ts ...
- Oracle常用SQL查询
一.ORACLE的启动和关闭 1.在单机环境下要想启动或关闭oracle系统必须首先切换到oracle用户,如下: su - oracle a.启动Oracle系统 oracle>svrmgrl ...
- IBatis.Net使用总结(一)-- IBatis解决SQL注入(#与$的区别)
IBatis解决SQL注入(#与$的区别) 在IBatis中,我们使用SqlMap进行Sql查询时,需要引用参数,在参数引用中可以使用两种占位符#和$.这两种占位符有什么区别呢? (1):#***#, ...
- 转:ibatis动态sql
转:ibatis动态sql 直接使用JDBC一个非常普遍的问题就是动态SQL.使用参数值.参数本身和数据列都是动态SQL,通常是非常困难的.典型的解决办法就是用上一堆的 IF-ELSE条件语句和一连串 ...
- Mysql 常用 SQL 语句集锦 转载(https://gold.xitu.io/post/584e7b298d6d81005456eb53)
Mysql 常用 SQL 语句集锦 基础篇 //查询时间,友好提示 $sql = "select date_format(create_time, '%Y-%m-%d') as day fr ...
随机推荐
- caffe整体框架的学习的博客,这个博客山寨了一个caffe框架
http://www.cnblogs.com/neopenx/default.html?page=1 这个博主很牛逼,写的东西也很好,多学学,无论是对框架,还是对自己学习c++帮助都非常大
- 通过sql语句查询出来的结果字段没有到对应实体类时的处理方法
通过sql语句查询出来的结果字段没有到对应实体类时的处理方法,对于Person类获取用户第一个名字和年龄两个字段,常见的有两种方式: 1.在创建一个与查询结果字段对应的类,然后通过构造函数实现: Qu ...
- PL/SQL知识点
1.ROW_NUMBER() OVER(PARTITION BY XXX ORDER BY XXX) SELECT STP.FLOW_INST_ID, BUU.USER_NAME, ORGG.NAME ...
- python序列化_json,pickle,shelve模块
序列化 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes 把内存数据 转成字符,叫序列化 把字符 转成内存数据,叫反序列化 模块 ...
- js中的AJAX
AJAX:Asynchronous JavaScript and XML.意思就是用JavaScript执行异步网络请求. 如果仔细观察一个Form的提交,你就会发现,一旦用户点击Submit按钮,表 ...
- Oracle 数据导出注意事项
1.数据导出exp.expbd和imp.impbd 区别: exp,imp:既可以在客户端执行也可以在服务端执行,效率慢于expbd.impbd expbd.impbd:只能够在服务端执行,impbd ...
- MySQL的数据类型(二)
MySQL中提供了多种对字符数据的存储类型,不同的版本可能有所差异.以5.0版本为例,MySQL包括了CHAR.VARCHAR.BINARY.VARBINARY.BLOB.TEXT等多种字符串类型. ...
- Gitlab简单使用指南
原文链接 一.在gitlab的网站创建一个project 定一个项目名,选定相关的项目设置,private,public等 项目创建成功后,得到项目git@XXX.git的地址,可用于将project ...
- js中FormData+XMLHttpRequest数据传输
前言: 首先我们需要了解,前后端进行数据传输依赖于浏览器的XMLHttpRequest对象 一.什么是XMLHttpRequest对象? XMLHttpRequest 是DOM对象,提供了对于http ...
- MySql Connector/C++8事务处理Demo
#include <iostream> #include <exception> #include <vector> #include <unistd.h&g ...