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高级应用的更多相关文章

  1. 【Mybatis高级映射】一对一映射、一对多映射、多对多映射

    前言 当我们学习heribnate的时候,也就是SSH框架的网上商城的时候,我们就学习过它对应的高级映射,一对一映射,一对多映射,多对多映射.对于SSM的Mybatis来说,肯定也是差不多的.既然开了 ...

  2. mybatis高级映射(一对一,一对多)

    mybatis高级映射 一对一关联映射 需求:查询订单信息,关联查询用户信息(一个订单对应一个用户) (1)通过resultType实现 sql语句: select orders.* , USER.u ...

  3. MyBatis高级篇之整合ehcache缓存框架

    MyBatis高级篇之整合ehcache缓存框架  2017-09-01  0 Comments  1,671 Views  0 Times 一.前言 MyBatis为我们提供了Cache接口,也提供 ...

  4. MyBatis高级查询

    -------------------------siwuxie095 MyBatis 高级查询 1.MyBatis 作为一个 ORM 框架,也对 SQL 的高级查询做了支持, MyBatis 高级查 ...

  5. mybatis 高级映射和spring整合之逆向工程(7)

    mybatis 高级映射和spring整合之逆向工程(7) 4.0 逆向工程 4.1 mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行 ...

  6. mybatis 高级映射和spring整合之与Spring整合(6)

    mybatis 高级映射和spring整合之mybatis与Spring整合 3.0 mybatis和spring整合(掌握) 3.1 整合思路 需求spring通过单例方式管理SqlSessionF ...

  7. mybatis 高级映射和spring整合之查询缓存(5)

    mybatis 高级映射和spring整合之查询缓存(5) 2.0 查询缓存 2.0.1 什么是查询缓存 mybatis提供缓存,用于减轻数据压力,提高数据库性能. mybatis提供一级缓存和二级缓 ...

  8. mybatis 高级映射和spring整合之高级映射(4)

    mybatis 高级映射和spring整合之高级映射 ----------------学习结构-------------------- 0.0 对订单商品数据模型进行分析 1.0 高级映射 1.1 一 ...

  9. Mybatis高级结果映射

    有时侯,我们用SQL取得的结果需要映射到类似Map<key, Bean>这样的数据结构中或是映射到多个实体类中时,我们就需要使用到resultMap.下面用3个例子说明Mybatis高级结 ...

  10. MyBatis 高级查询环境准备(八)

    MyBatis 高级查询 之前在学习 Mapper XML 映射文件时,说到 resultMap 标记是 MyBatis 中最重要最强大也是最复杂的标记,而且还提到后面会详细介绍它的高级用法. 听到高 ...

随机推荐

  1. 码云分布式之 Brzo 服务器

    摘要: 码云是国内最大的代码托管平台,为了支持更大的用户规模,开发团队也在对一些组件进行大规模的重构. 前言 码云是国内最大的代码托管平台.码云基于 Gitlab 5.5 开发,经过几年的开发已经和官 ...

  2. bzoj2257

    不难发现其实这个捣鼓过程就是一个辗转相减所以最小燃料是瓶容量的最小公约数然后穷举约数即可 ..] of longint; n,k,x,i,m,j,t:longint; procedure sort(l ...

  3. wikioi 1514 and ZJOI2006 书架

    1514 书架 0人推荐 收藏 发题解 提交代码 报错 题目描述 输入描述 输出描述 样例输入 样例输出 提示 题目描述 Description 小 T有一个很大的书柜.这个书柜的构造有些独特,即书柜 ...

  4. “面包屑导航”——SiteMapPath控件的使用(ASP.NET)(转)

    转自:http://www.cnblogs.com/ball-head/archive/2010/09/28/1837253.html 最近在博客里写了一些日志,主要都是我在实际编程过程中遇到的问题. ...

  5. Linux下Chrome浏览器的BUG

    “我胡汉三又回来了”,好久没出现在博客园了,准备考试什么的最烦躁了,今天又重新整了下我的Ubuntu,结果发现了一个Chrome浏览器的Bug,但是与其说它是个Bug,还不如说它是个Joke. 好吧, ...

  6. vi find和grep

    linux grep和find命令 linux中强大且常用命令:find.grep 源码搜索:find . -name "*.xml" | xargs grep -Hna &quo ...

  7. python urllib2模块携带cookie

    今天干活遇到一个事.有一些网站的一些操作非得要求你登陆才能做,比如新浪微博,你要随便看看吧,不行,非得让你登陆了才能看,再比如一些用户操作,像更改自己的资料啦,个人的隐私啦巴拉巴拉的.想抓取这样的ur ...

  8. ARM学习笔记13——LED驱动程序设计

    首先我们要根据开发板原理图得到控制LED灯的引脚是哪个,我们现在以LED1为例,我们已经知道LED1由S5PV210的GPC1_3控制,因此我们按如下步骤进行: 第一步是配制S5PV210的GPC1_ ...

  9. Opencl API解释(二)

    欢迎关注,转载引用请注明 http://blog.csdn.net/leonwei/article/details/8909897 这里将更深入的说明一些OpenCL API的功能 1. 创建buff ...

  10. 一起来说 Vim 语

    作为一款古老而具有持久生命力的编辑器,vim 自有它的强大之处.很多人觉得 Vim 的学习曲线太陡峭了,为了能够把 Vim 用得风生水起,不得不记忆大量的命令.如果你是 Vim 新手,刚入门就开始面对 ...