ibaits数据库映射表的sql查寻数据映射时,映射的是正整数是怎么映射

Suggested actions
If you typed the address, please make sure that the spelling is correct.Note: Most addresses are case sensitive.
For information on IBM offerings, start from the .
For information on printing systems, start from the .*
Get assistance
This option lets you send an information request and tell us about a broken link. You will receive an e-mail from us to help you find what you need.
504 Gateway Time-out
Self-help resourcesThe page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.The page is temporarily unavailable
nginx error!
The page you are looking for is temporarily unavailable.
Please try again later.
Website Administrator
Something has triggered an error on your
This is the default error page for
nginx that is distributed with
It is located
/usr/share/nginx/html/50x.html
You should customize this error page for your own
site or edit the error_page directive in
the nginx configuration file
/etc/nginx/nginx.conf.ibatis 16个ibatis常用的SQL语句代码 - 为程序员服务
为程序员服务
16个ibatis常用的SQL语句代码
(1) 输入参数为单个值
&delete id=&com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore&
parameterClass=&long&&
delete from
MemberAccessLog
accessTimestamp = #value#
&delete id=&com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore&
parameterClass=&long&&
delete from
MemberAccessLog
accessTimestamp = #value#
(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,
#accessLogId#, #memberId#,
#clientIP#, #httpMethod#,
#actionId#, #requestURL#,
#accessTimestamp#, #extend1#,
#extend2#, #extend3#
&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,
#accessLogId#, #memberId#,
#clientIP#, #httpMethod#,
#actionId#, #requestURL#,
#accessTimestamp#, #extend1#,
#extend2#, #extend3#
(3) 输入参数为一个java.util.HashMap
&select id=&com.fashionfree.stat.accesslog.selectActionIdAndActionNumber&
parameterClass=&hashMap&
resultMap=&getActionIdAndActionNumber&&
actionId, count(*) as count
MemberAccessLog
memberId = #memberId#
and accessTimestamp & #start#
and accessTimestamp &= #end#
group by actionId
&select id=&com.fashionfree.stat.accesslog.selectActionIdAndActionNumber&
parameterClass=&hashMap&
resultMap=&getActionIdAndActionNumber&&
actionId, count(*) as count
MemberAccessLog
memberId = #memberId#
and accessTimestamp & #start#
and accessTimestamp &= #end#
group by actionId
(4) 输入参数中含有数组
&insert id=&updateStatusBatch& parameterClass=&hashMap&&
status = #status#
&dynamic prepend=&where questionId in&&
&isNotNull property=&actionIds&&
&iterate property=&actionIds& open=&(& close=&)& conjunction=&,&&
#actionIds[]#
&/iterate&
&/isNotNull&
&/dynamic&
&insert id=&updateStatusBatch& parameterClass=&hashMap&&
status = #status#
&dynamic prepend=&where questionId in&&
&isNotNull property=&actionIds&&
&iterate property=&actionIds& open=&(& close=&)& conjunction=&,&&
#actionIds[]#
&/iterate&
&/isNotNull&
&/dynamic&
说明:actionIds为传入的数组的名字;
使用dynamic标签避免数组为空时导致sql语句语法出错;
使用isNotNull标签避免数组为null时ibatis解析出错
(5)传递参数只含有一个数组
&select id=&com.fashionfree.stat.accesslog.model.StatMemberAction.selectActionIdsOfModule&
resultClass=&hashMap&&
moduleId, actionId
StatMemberAction
&dynamic prepend=&where moduleId in&&
&iterate open=&(& close=&)& conjunction=&,&&
&/iterate&
&/dynamic&
&select id=&com.fashionfree.stat.accesslog.model.StatMemberAction.selectActionIdsOfModule&
resultClass=&hashMap&&
moduleId, actionId
StatMemberAction
&dynamic prepend=&where moduleId in&&
&iterate open=&(& close=&)& conjunction=&,&&
&/iterate&
&/dynamic&
说明:注意select的标签中没有parameterClass一项
另:这里也可以把数组放进一个hashMap中,但增加额外开销,不建议使用
(6)让ibatis把参数直接解析成字符串
&select id=&com.fashionfree.stat.accesslog.selectSumDistinctCountOfAccessMemberNum&
parameterClass=&hashMap& resultClass=&int&&
count(distinct memberId)
MemberAccessLog
accessTimestamp &= #start#
and accessTimestamp & #end#
and actionId in $actionIdString$
&select id=&com.fashionfree.stat.accesslog.selectSumDistinctCountOfAccessMemberNum&
parameterClass=&hashMap& resultClass=&int&&
count(distinct memberId)
MemberAccessLog
accessTimestamp &= #start#
and accessTimestamp & #end#
and actionId in $actionIdString$
说明:使用这种方法存在sql注入的风险,不推荐使用
(7)分页查询 (pagedQuery)
&select id=&com.fashionfree.stat.accesslog.selectMemberAccessLogBy&
parameterClass=&hashMap& resultMap=&MemberAccessLogMap&&
&include refid=&selectAllSql&/&
&include refid=&whereSql&/&
&include refid=&pageSql&/&
&select id=&com.fashionfree.stat.accesslog.selectMemberAccessLogBy.Count&
parameterClass=&hashMap& resultClass=&int&&
&include refid=&countSql&/&
&include refid=&whereSql&/&
&sql id=&selectAllSql&&
accessLogId, memberId, clientIP,
httpMethod, actionId, requestURL,
accessTimestamp, extend1, extend2,
MemberAccessLog
&sql id=&whereSql&&
accessTimestamp &= #accessTimestamp#
&sql id=&countSql&&
MemberAccessLog
&sql id=&pageSql&&
&isNotNull property=&startIndex&&
&isNotNull property=&pageSize&&
limit #startIndex# , #pageSize#
&/isNotNull&
&/isNotNull&
&/dynamic&
&select id=&com.fashionfree.stat.accesslog.selectMemberAccessLogBy&
parameterClass=&hashMap& resultMap=&MemberAccessLogMap&&
&include refid=&selectAllSql&/&
&include refid=&whereSql&/&
&include refid=&pageSql&/&
&select id=&com.fashionfree.stat.accesslog.selectMemberAccessLogBy.Count&
parameterClass=&hashMap& resultClass=&int&&
&include refid=&countSql&/&
&include refid=&whereSql&/&
&sql id=&selectAllSql&&
accessLogId, memberId, clientIP,
httpMethod, actionId, requestURL,
accessTimestamp, extend1, extend2,
MemberAccessLog
&sql id=&whereSql&&
accessTimestamp &= #accessTimestamp#
&sql id=&countSql&&
MemberAccessLog
&sql id=&pageSql&&
&isNotNull property=&startIndex&&
&isNotNull property=&pageSize&&
limit #startIndex# , #pageSize#
&/isNotNull&
&/isNotNull&
&/dynamic&
说明:本例中,代码应为:
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
accessTimestamp &= #value#
&delete id=&com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore& parameterClass=&long&&
delete from
MemberAccessLog
accessTimestamp &= #value#
将特殊字符放在xml的CDATA区内:
&delete id=&com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore& parameterClass=&long&&
delete from
MemberAccessLog
accessTimestamp &= #value#
&delete id=&com.fashionfree.stat.accesslog.deleteMemberAccessLogsBefore& parameterClass=&long&&
delete from
MemberAccessLog
accessTimestamp &= #value#
推荐使用第一种方式,写为& 和 & (XML不对CDATA里的内容进行解析,因此如果CDATA中含有dynamic标签,将不起作用)
(9)include和sql标签
将常用的sql语句整理在一起,便于共用:
&sql id=&selectBasicSql&&
samplingTimestamp,onlineNum,year,
month,week,day,hour
OnlineMemberNum
&sql id=&whereSqlBefore&&
where samplingTimestamp &= #samplingTimestamp#
&select id=&com.fashionfree.accesslog.selectOnlineMemberNumsBeforeSamplingTimestamp& parameterClass=&hashmap& resultClass=&OnlineMemberNum&&
&include refid=&selectBasicSql& /&
&include refid=&whereSqlBefore& /&
&sql id=&selectBasicSql&&
samplingTimestamp,onlineNum,year,
month,week,day,hour
OnlineMemberNum
&sql id=&whereSqlBefore&&
where samplingTimestamp &= #samplingTimestamp#
&select id=&com.fashionfree.accesslog.selectOnlineMemberNumsBeforeSamplingTimestamp& parameterClass=&hashmap& resultClass=&OnlineMemberNum&&
&include refid=&selectBasicSql& /&
&include refid=&whereSqlBefore& /&
注意:sql标签只能用于被引用,不能当作mapped statement。如上例中有名为selectBasicSql的sql元素,试图使用其作为sql语句执行是错误的:
sqlMapClient.queryForList(“selectBasicSql”); ×
(10)随机选取记录
&sql id=”randomSql”&
ORDER BY rand() LIMIT #number#
&sql id=”randomSql”&
ORDER BY rand() LIMIT #number#
从数据库中随机选取number条记录(只适用于MySQL)
(11)将SQL GROUP BY分组中的字段拼接
&sql id=”selectGroupBy&
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
AnswererCategory a, QuestionCategory q
WHERE a.questionCategoryId = q.questionCategoryId
GROUP BY a.answererId
ORDER BY a.answererCategoryId
&sql id=”selectGroupBy&
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
AnswererCategory a, QuestionCategory q
WHERE a.questionCategoryId = q.questionCategoryId
GROUP BY a.answererId
ORDER BY a.answererCategoryId
注:SQL中使用了MySQL的GROUP_CONCAT函数
(12) 按照IN里面的顺序进行排序
&sql id=”groupByInArea”&
moduleId, moduleName,
status, lastModifierId, lastModifiedName,
lastModified
StatModule
moduleId in (3, 5, 1)
instr(',3,5,1,' , ','+ltrim(moduleId)+',')
&sql id=”groupByInArea”&
moduleId, moduleName,
status, lastModifierId, lastModifiedName,
lastModified
StatModule
moduleId in (3, 5, 1)
instr(',3,5,1,' , ','+ltrim(moduleId)+',')
②SQLSERVER:
&sql id=”groupByInArea”&
moduleId, moduleName,
status, lastModifierId, lastModifiedName,
lastModified
StatModule
moduleId in (3, 5, 1)
charindex(','+ltrim(moduleId)+',' , ',3,5,1,')
&sql id=”groupByInArea”&
moduleId, moduleName,
status, lastModifierId, lastModifiedName,
lastModified
StatModule
moduleId in (3, 5, 1)
charindex(','+ltrim(moduleId)+',' , ',3,5,1,')
说明:查询结果将按照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&&
&isEqual property=&tag& compareValue=&1&&
, userName
&/isEqual&
&isEqual property=&tag& compareValue=&2&&
, userPassword
&/isEqual&
&select id=&testForRemap& parameterClass=&hashMap& resultClass=&hashMap& remapResults=&true&&
&isEqual property=&tag& compareValue=&1&&
, userName
&/isEqual&
&isEqual property=&tag& compareValue=&2&&
, userPassword
&/isEqual&
此例中,根据参数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 id=&whereSql&&
&dynamic prepend=&where &&
&isNotNull property=&userId& prepend=&BOGUS&&
userId = #userId#
&/isNotNull&
&isNotEmpty property=&userName& prepend=&and &&
userName = #userName#
&/isNotEmpty&
&/dynamic&
此例中,dynamic标签中含有两个子标签&isNotNull&和&isNotEmpty&。根据前面叙述的原则,如果&isNotNull&标签中没有prepend="BOGUS" 这一假的属性来让dynamic去掉的话,&isNotEmpty&标签中的and就会被忽略,会造成sql语法错误。
注意:当dynamic标签没有prepend属性时,不会自动忽略其子标签的第一个prepend属性。
您可能的代码
相关聚客文章
荣誉:2076
相关专栏文章MyBatis之SQL语句映射文件增删改查和Java参数如何对应 - 开源中国社区
当前访客身份:游客 [
当前位置:
转载 /blog/781911
select 一个select 元素非常简单。例如:
&!-- 查询学生,根据id --&
&select id=&getStudent& parameterType=&String& resultMap=&studentResultMap&&
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.CLASS_ID
FROM STUDENT_TBL ST
WHERE ST.STUDENT_ID = #{studentID}
这条语句就叫做‘getStudent,有一个String参数,并返回一个StudentEntity类型的对象。
注意参数的标识是:#{studentID}。
select 语句属性配置细节:
属性 && &描述 && &取值 && &默认
id && &在这个模式下唯一的标识符,可被其它语句引用 && &&& &
parameterType && &传给此语句的参数的完整类名或别名 && &&& &
resultType && &语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用) && &&& &
resultMap && &引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用) && &&& &
flushCache && &如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false && &true|false && &false
useCache && &如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout &&& &设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 && &正整数 && &未设置
fetchSize && &设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 && &正整数 && &驱动器决定
statementType && &statement,preparedstatement,callablestatement。
一个简单的insert语句:
&!-- 插入学生 --&
&insert id=&insertStudent& parameterType=&StudentEntity&&
INSERT INTO STUDENT_TBL (STUDENT_ID,
STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
(#{studentID},
#{studentName},
#{studentSex},
#{studentBirthday},
#{classEntity.classID})
insert可以使用数据库支持的自动生成主键策略,设置useGeneratedKeys=”true”,然后把keyProperty 设成对应的列,就搞定了。比如说上面的StudentEntity 使用auto-generated 为id 列生成主键.
&还可以使用selectKey元素。下面例子,使用mysql数据库nextval('student')为自定义函数,用来生成一个key。
&!-- 插入学生 自动主键--&
&insert id=&insertStudentAutoKey& parameterType=&StudentEntity&&
&selectKey keyProperty=&studentID& resultType=&String& order=&BEFORE&&
select nextval('student')
&/selectKey&
INSERT INTO STUDENT_TBL (STUDENT_ID,
STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
(#{studentID},
#{studentName},
#{studentSex},
#{studentBirthday},
#{classEntity.classID})
insert语句属性配置细节:
属性 && &描述 && &取值 && &默认
id && &在这个模式下唯一的标识符,可被其它语句引用 && &&& &
parameterType && &传给此语句的参数的完整类名或别名 && &&& &
flushCache && &如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false && &true|false && &false
useCache && &如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout &&& &设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 && &正整数 && &未设置
fetchSize && &设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 && &正整数 && &驱动器决定
statementType && & STATEMENT,PREPARED,CALLABLE && &PREPARED
useGeneratedKeys &&& 告诉MyBatis 使用JDBC 的getGeneratedKeys 方法来获取数据库自己生成的主键(MySQL、SQLSERVER 等
关系型数据库会有自动生成的字段)。默认:false& true|false && &false
keyProperty && &
标识一个将要被MyBatis 设置进getGeneratedKeys 的key 所返回的值,或者为insert 语句使用一个selectKey子元素。
selectKey语句属性配置细节:
属性 && &描述 && &取值
keyProperty && &selectKey 语句生成结果需要设置的属性。 && &
resultType && &生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int类型。 && &
order && &可以设成BEFORE 或者AFTER,如果设为BEFORE,那它会先选择主键,然后设置keyProperty,再执行insert语句;如果设为AFTER,它就先运行insert 语句再运行selectKey 语句,通常是insert 语句中内部调用数据库(像Oracle)内嵌的序列机制。 &&& &BEFORE
statementType && &像上面的那样, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement ,PreparedStatement 和CallableStatement 响应 && &STATEMENT,PREPARED,CALLABLE
update、delete
一个简单的update:
&!-- 更新学生信息 --&
&update id=&updateStudent& parameterType=&StudentEntity&&
UPDATE STUDENT_TBL
SET STUDENT_TBL.STUDENT_NAME = #{studentName},
STUDENT_TBL.STUDENT_SEX = #{studentSex},
STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
STUDENT_TBL.CLASS_ID = #{classEntity.classID}
WHERE STUDENT_TBL.STUDENT_ID = #{studentID};
一个简单的delete:
&!-- 删除学生 --&
&delete id=&deleteStudent& parameterType=&StudentEntity&&
DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID}
update、delete语句属性配置细节:
属性 && &描述 && &取值 && &默认
id && &在这个模式下唯一的标识符,可被其它语句引用 && &&& &
parameterType && &传给此语句的参数的完整类名或别名 && &&& &
flushCache && &如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false && &true|false && &false
useCache && &如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 && &true|false && &false
timeout &&& &设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 && &正整数 && &未设置
fetchSize && &设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 && &正整数 && &驱动器决定
statementType && &statement,preparedstatement,callablestatement。
Sql元素用来定义一个可以复用的SQL 语句段,供其它语句调用。比如:
&!-- 复用sql语句
查询student表所有字段 --&
&sql id=&selectStudentAll&&
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.CLASS_ID
FROM STUDENT_TBL ST
&这样,在select的语句中就可以直接引用使用了,将上面select语句改成:
&!-- 查询学生,根据id --&
&select id=&getStudent& parameterType=&String& resultMap=&studentResultMap&&
&include refid=&selectStudentAll&/&
WHERE ST.STUDENT_ID = #{studentID}
parameters
&&&&&&& 上面很多地方已经用到了参数,比如查询、修改、删除的条件,插入,修改的数据等,MyBatis可以使用的基本数据类型和Java的复杂数据类型。
&&&&&&& 基本数据类型,String,int,date等。
&&&&&&& 但是使用基本数据类型,只能提供一个参数,所以需要使用Java实体类,或Map类型做参数类型。通过#{}可以直接得到其属性。
1基本类型参数
根据入学时间,检索学生列表:
&!-- 查询学生list,根据入学时间
&select id=&getStudentListByDate&
parameterType=&Date& resultMap=&studentResultMap&&
FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID
WHERE CT.CLASS_YEAR = #{classYear};
List&StudentEntity& studentList = studentMapper.getStudentListByClassYear(StringUtil.parse(&&));
for (StudentEntity entityTemp : studentList) {
System.out.println(entityTemp.toString());
2Java实体类型参数
根据姓名和性别,检索学生列表。使用实体类做参数:
&!-- 查询学生list,like姓名、=性别,参数entity类型 --&
&select id=&getStudentListWhereEntity& parameterType=&StudentEntity& resultMap=&studentResultMap&&
SELECT * from STUDENT_TBL ST
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
AND ST.STUDENT_SEX = #{studentSex}
StudentEntity entity = new StudentEntity();
entity.setStudentName(&李&);
entity.setStudentSex(&男&);
List&StudentEntity& studentList = studentMapper.getStudentListWhereEntity(entity);
for (StudentEntity entityTemp : studentList) {
System.out.println(entityTemp.toString());
根据姓名和性别,检索学生列表。使用Map做参数:
&!-- 查询学生list,=性别,参数map类型 --&
&select id=&getStudentListWhereMap& parameterType=&Map& resultMap=&studentResultMap&&
SELECT * from STUDENT_TBL ST
WHERE ST.STUDENT_SEX = #{sex}
AND ST.STUDENT_SEX = #{sex}
Map&String, String& map = new HashMap&String, String&();
map.put(&sex&, &女&);
map.put(&name&, &李&);
List&StudentEntity& studentList = studentMapper.getStudentListWhereMap(map);
for (StudentEntity entityTemp : studentList) {
System.out.println(entityTemp.toString());
4多参数的实现
如果想传入多个参数,则需要在接口的参数上添加@Param注解。给出一个实例:
接口写法:
public List&StudentEntity& getStudentListWhereParam(@Param(value = &name&) String name, @Param(value = &sex&) String sex, @Param(value = &birthday&) Date birthdar, @Param(value = &classEntity&) ClassEntity classEntity);
&!-- 查询学生list,like姓名、=性别、=生日、=班级,多参数方式 --&
&select id=&getStudentListWhereParam& resultMap=&studentResultMap&&
SELECT * from STUDENT_TBL ST
&if test=&name!=null and name!='' &&
ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
&if test=&sex!= null and sex!= '' &&
AND ST.STUDENT_SEX = #{sex}
&if test=&birthday!=null&&
AND ST.STUDENT_BIRTHDAY = #{birthday}
&if test=&classEntity!=null and classEntity.classID !=null and classEntity.classID!='' &&
AND ST.CLASS_ID = #{classEntity.classID}
&/select& 进行查询:Java代码
List&StudentEntity& studentList = studentMapper.getStudentListWhereParam(&&, &&,StringUtil.parse(&&), classMapper.getClassByID(&&));
for (StudentEntity entityTemp : studentList) {
System.out.println(entityTemp.toString());
5字符串代入法
&&&&&&& 默认的情况下,使用#{}语法会促使MyBatis 生成PreparedStatement 属性并且使用PreparedStatement 的参数(=?)来安全的设置值。尽量这些是快捷安全,也是经常使用的。但有时候你可能想直接未更改的字符串代入到SQL 语句中。比如说,对于ORDER BY,你可能会这样使用:ORDER BY ${columnName}但MyBatis 不会修改和规避掉这个字符串。
&&&&&&& 注意:这样地接收和应用一个用户输入到未更改的语句中,是非常不安全的。这会让用户能植入破坏代码,所以,要么要求字段不要允许客户输入,要么你直接来检测他的合法性 。
原文链接:
共有0个评论
更多开发者职位上
有什么技术问题吗?
晨曦之光的其它问题
类似的话题

我要回帖

更多关于 数据库映射表 的文章

 

随机推荐