Mybatis高级应用
Mybatis是一个半自动的框架。相对于hibernate全自动模式,mybatis为开发人员提供了更加灵活的对sql语句操作的控制能力,有利于dba对相关的sql操作进行优化,同时也方便开发者构建复杂的sql操作。以下是Mybatis的相关高级应用,以供参考。
Mybatis的官方文档:http://mybatis.github.io/mybatis-3/zh/index.html
- 通过配置类进行构建SqlSessionFactory
Mybatis允许通过xml或配置类构建SqlSessionFactory
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
通过SqlSessionFactory获取SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
} finally {
session.close();
}
- forEach应用
forEach按照官方支持对单一数组和集合进行遍历,以下是对单一数组进行遍历的示例,集合参数其实是类似的
<delete id="deleteFile" parameterType="HashMap">
delete
From tbl_File
Where themeKey = #{themeKey}
<trim suffixOverrides="and">
<if test="arrFileUrl != null and arrFileUrl != '' ">
And fileUrl in
<foreach item="item" index="index" collection="arrFileUrl"
open="(" separator="," close=")">
#{item}
</foreach>
</if>
</trim>
</delete>
调用方法:
HashMap<String, Object> argMap = new HashMap<String, Object>();
argMap.put("themeKey", themeKey);
/*arrFileUrl 是一个字符串数组*/
argMap.put("arrFileUrl", arrFileUrl); deleteFile(HashMap<String, Object> argMap);
foreach支持遍历list,map,array 三种类型,因此利用foreach以上特性实现批量插入数据功能。
<insert id="addTrainRecordBatch" useGeneratedKeys="true" parameterType="java.util.List">
<selectKey resultType="long" keyProperty="id" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey> insert into t_train_record (add_time,emp_id,activity_id,flag)
values <foreach collection="list" item="item" index="index" separator="," >
(#{item.addTime},#{item.empId},#{item.activityId},#{item.flag})
</foreach>
</insert>
- collection应用
<resultMap id="Guide" type="Guide">
<id column="spaguideKey" property="guideKey"/>
<result column="GUIDENAME" property="guideName"/>
<result column="GRADE" property="grade"/>
<result column="gradeName" property="gradeName"/>
<result column="SUBJECT" property="subject"/>
<result column="subjectName" property="subjectName"/>
<result column="CREATECODE" property="createCode"/>
<result column="realName" property="realName"/>
<result column="CREATETIME" property="createTime"/>
<result column="ISVALID" property="isValid"/>
<result column="ISREVIEW" property="isReview"/>
<result column="CONTENT" property="content"/> <collection property="guideVideoList" ofType="GuideVideo">
<id column="spavideokey" property="videoKey"/>
<result column="videoName" property="videoName"/>
<result column="videoFileUrl" property="fileUrl"/>
</collection>
<collection property="guideArchiveList" ofType="GuideArchive">
<id column="SPAARCHIVESKEY" property="archiveKey"/>
<result column="archiveName" property="archiveName"/>
<result column="archiveFileUrl" property="fileUrl"/>
</collection>
</resultMap> <select id="getGuide" parameterType="Guide" resultMap="Guide">
Select
sg.SPAGUIDEKEY,
GUIDENAME,
CREATETIME,
CONTENT,
grade,
gradeName,
subject,
subjectName,
CREATECODE,
realName,
spavideokey,
videoName,
videoFileName,
videoFileUrl,
SPAARCHIVESKEY,
ARCHIVENAME,
archiveFileName,
archiveFileUrl
from vw_spa_guide sg
left join vw_spa_guide_video sgv on sgv.spaguidekey = sg.spaguidekey
left join vw_spa_guide_archive sga on sga.spaguidekey = sg.spaguidekey
</select>
- Mybatis 嵌套查询
<resultMap type="User" id="userResultMap">
<id property="id" column="user_id" />
<result property="userName" column="user_userName" />
<result property="userAge" column="user_userAge" />
<result property="userAddress" column="user_userAddress" />
</resultMap> <resultMap id="articleResultMap" type="Article">
<id property="id" column="article_id" />
<result property="title" column="article_title" />
<result property="content" column="article_content" />
<association property="user" javaType="User" resultMap="userResultMap"/>
</resultMap> <select id="getUserArticles" parameterType="int" resultMap="articleResultMap">
select user.id user_id,user.userName user_userName,user.userAddress user_userAddress,
article.id article_id,article.title article_title,article.content article_content
from user,article
where user.id=article.userid and user.id=#{id}
</select>
借用别人的例子来说明。
- mybatis 自定义主键
<insert id="insertTest" parameterType="Test">
<selectKey keyProperty="testKey" order="BEFORE" resultType="String">
SELECT SEQ_TST_TEST.nextval
FROM DUAL
</selectKey> insert into TST_TEST(
TESTKEY,
TESTNAME
)values(
#{testKey},
#{testName}
)
</insert>
mybatis 相对于oracle的自增长先进行查询读取下一个主键,oracle不支持useGeneratedKeys,然后再进行插入操作。相对于其他数据库可以采用如下方式
<insert id="insertTest" parameterType="Test" useGeneratedKeys="true" keyProperty="testKey">
insert into Test(testKey, testName)
values(#{testKey},#{testName})
</insert>
- mybatis复用语句块
<!--定义可重用的SQL代码段-->
<sql id="multiplexSql">testKey, testName</sql> <select id="getTest" parameterType="int" resultType="hashmap">
select
<include refid="multiplexSql"/>
from Blog
where id = #{testKey}
</select>
- Mybatis执行函数,返回结果集
<select id="getSelfStatisticData" parameterType="HashMap" statementType="CALLABLE" >
{#{result,mode=OUT,jdbcType=CURSOR, resultMap=SelfStatisticData} = call PKG_RRT_SelfStatics.Fn_GetSelfStatData(#{userCode,jdbcType=VARCHAR,mode=IN})}
</select>
Java调用的代码
public interface SelfStatisticDataDao {
public List<SelfStatisticData> getSelfStatisticData(Map<String, Object> statMap);
}
statMap 中的键值对对应着Fn_GetSelfStatData()函数的参数,键名与参数名保持完全一致,区分大小写。
SelfStatisticData定义的实体保持与结果集的字段一致。
- Mybatis执行没有返回值的存储过程
<select id="insertGuideIntegral" parameterType="HashMap" statementType="CALLABLE" >
{
call PKG_Center_Integral_guide.Pro_SyncGuideIntegral(
#{userCode,jdbcType=VARCHAR,mode=IN},
#{integralKey,jdbcType=VARCHAR,mode=IN},
#{gradeKey,jdbcType=VARCHAR,mode=IN},
#{subjectKey,jdbcType=VARCHAR,mode=IN}
)
}
</select>
- Mybatis执行带有返回两个游标结果集和输出参数
<resultMap type="IntegralResult" id="integralResult">
<result column="integralKey" property="integralKey"/>
<result column="integralName" property="integralName"/>
</resultMap> <resultMap type="GuideIntegralResult" id="guideIntegralResult">
<result column="guideIntegralKey" property="guideIntegralKey"/>
<result column="guideIntegralName" property="guideIntegralName"/>
</resultMap> <select id="get" parameterType="java.util.Map" statementType="CALLABLE" resultMap="integralResult, guideIntegralResult">
{
call PKG_Center_Integral_guide.Pro_GuideIntegral(
#{userCode,jdbcType=VARCHAR,mode=IN},
#{subjectKey,jdbcType=VARCHAR,mode=IN},
#{userName, mode=OUT, jdbcType=String}
)
}
</select>
- Mybatis 支持结构体类型
#{middleInitial, mode=OUT, jdbcType=STRUCT, jdbcTypeName=MY_TYPE, resultMap=departmentResultMap}
MY_TYPE为数据库中自定义的结构体
- 定义输入输出小数点
#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}
- 使用association进行复杂映射
<resultMap type="Blog" id="Blog_result">
<id column="id" property="id" />
<result column="title" property="title"/> <!-- 映射关联的对象 -->
<association property="author" javaType="Author">
<id column="author_id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="email" property="email"/>
<result column="bio" property="bio"/>
</association>
</resultMap> <select id="selectBlog_by_id" parameterType="int" resultMap="Blog_result">
select
b.id,
b.title,
b.author_id,
a.id,
a.username,
a.password,
a.email,
a.bio
from Blog b
left join Author a on b.author_id = a.id
where b.id = #{id}
</select>
- 定义输入输出和指定游标结果集
#{
department,
mode=OUT,
jdbcType=CURSOR,
javaType=ResultSet,
resultMap=departmentResultMap
}
mode属性允许你指定IN,OUT或INOUT参数。如果mode为OUT(或INOUT),而且jdbcType为CURSOR(也就是Oracle的REFCURSOR),你必须指定一个resultMap来映射结果集到参数类型。
- 参考资料
http://blog.csdn.net/rootsuper/article/details/8542236
Mybatis高级应用的更多相关文章
- 【Mybatis高级映射】一对一映射、一对多映射、多对多映射
前言 当我们学习heribnate的时候,也就是SSH框架的网上商城的时候,我们就学习过它对应的高级映射,一对一映射,一对多映射,多对多映射.对于SSM的Mybatis来说,肯定也是差不多的.既然开了 ...
- mybatis高级映射(一对一,一对多)
mybatis高级映射 一对一关联映射 需求:查询订单信息,关联查询用户信息(一个订单对应一个用户) (1)通过resultType实现 sql语句: select orders.* , USER.u ...
- MyBatis高级篇之整合ehcache缓存框架
MyBatis高级篇之整合ehcache缓存框架 2017-09-01 0 Comments 1,671 Views 0 Times 一.前言 MyBatis为我们提供了Cache接口,也提供 ...
- MyBatis高级查询
-------------------------siwuxie095 MyBatis 高级查询 1.MyBatis 作为一个 ORM 框架,也对 SQL 的高级查询做了支持, MyBatis 高级查 ...
- mybatis 高级映射和spring整合之逆向工程(7)
mybatis 高级映射和spring整合之逆向工程(7) 4.0 逆向工程 4.1 mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行 ...
- mybatis 高级映射和spring整合之与Spring整合(6)
mybatis 高级映射和spring整合之mybatis与Spring整合 3.0 mybatis和spring整合(掌握) 3.1 整合思路 需求spring通过单例方式管理SqlSessionF ...
- mybatis 高级映射和spring整合之查询缓存(5)
mybatis 高级映射和spring整合之查询缓存(5) 2.0 查询缓存 2.0.1 什么是查询缓存 mybatis提供缓存,用于减轻数据压力,提高数据库性能. mybatis提供一级缓存和二级缓 ...
- mybatis 高级映射和spring整合之高级映射(4)
mybatis 高级映射和spring整合之高级映射 ----------------学习结构-------------------- 0.0 对订单商品数据模型进行分析 1.0 高级映射 1.1 一 ...
- Mybatis高级结果映射
有时侯,我们用SQL取得的结果需要映射到类似Map<key, Bean>这样的数据结构中或是映射到多个实体类中时,我们就需要使用到resultMap.下面用3个例子说明Mybatis高级结 ...
- MyBatis 高级查询环境准备(八)
MyBatis 高级查询 之前在学习 Mapper XML 映射文件时,说到 resultMap 标记是 MyBatis 中最重要最强大也是最复杂的标记,而且还提到后面会详细介绍它的高级用法. 听到高 ...
随机推荐
- [转贴]gsoap使用心得!
最近换了个工作环境,现在在大望路这边上班,呵,刚上班接到的任务就是熟悉gsoap!废话少说,现在开始gSoap学习! gSOAP是一个夸平台的,用于开发Web Service服务端和客户端的工具,在W ...
- USB C和USB 3.1傻傻分不清?这篇文章可以帮你
USB Type-C接口以及USB 3.1标准的到来,理应为消费者提供更多便利.然而就目前来看,似乎这些新标准非但没有为消费者提供了更好的使用体验,反而带来了诸多隐患.Google的工程师Benson ...
- 用sql增、修改、删除字段
--给一个表增加一个字段 ); --给一个表修改一个字段的数据类型 ,); --通用sql修改字段的用法 ,); --删除一个字段 alter table wm_goods drop column b ...
- oracle报错ORA-01507
SHUTDOWN IMMEDIATE; STARTUP NOMOUNT; CONTROL1.CTL文件复制到CONTROL2.CTL; ALTER SYSTEM SET CONTROL_FILES=' ...
- java 图片文件格式转换(多页tif转jpg 、jpg转tif)
package util; import java.awt.image.RenderedImage; import java.awt.image.renderable.ParameterBlock; ...
- Delta-wave
Delta-wave Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...
- ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA
Centos5.5 安装Oracle11g客户端,配置了本地的net服务后,用sqlplus连接报错: tnsnames.ora配置如下 orcl = (DESCRIPTION = (ADDRESS ...
- [Qt]Qt中TreeWidget拖拽事件
文章在简书里啦 http://www.jianshu.com/p/45b740060aca
- jQuery获取和设置disabled属性、背景图片路径
之前对于这个独特的disabled属性获取和设置很混乱,今天项目中用到了,用attr不能实现,于是多次试验得出: 获取disabled属性用prop $("#basic_key") ...
- JavaScript高级程序设计33.pdf
操作样式表 CSSStyleSheet类型表示的是样式表包括通过<link>元素包含的样式表和在<style>元素中定义的样式表,前面提到过这两个元素本身分别是由HTMLLin ...