Mybatis高级应用

来源:互联网 发布:淘宝怎样设置下架时间 编辑:程序博客网 时间:2024/05/18 21:06

转自:http://blog.csdn.net/zouqingfang/article/details/44782999


   Mybatis是一个半自动的框架。相对于hibernate全自动模式,mybatis为开发人员提供了更加灵活的对sql语句操作的控制能力,有利于dba对相关的sql操作进行优化,同时也方便开发者构建复杂的sql操作。以下是Mybatis的相关高级应用,以供参考。

         Mybatis的官方文档:http://mybatis.github.io/mybatis-3/zh/index.html

  • 通过配置类进行构建SqlSessionFactory

             Mybatis允许通过xml或配置类构建SqlSessionFactory

[java] view plain copy
 print?
  1.         DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();  
  2.         TransactionFactory transactionFactory = new JdbcTransactionFactory();  
  3.         Environment environment = new Environment("development", transactionFactory, dataSource);  
  4.         Configuration configuration = new Configuration(environment);  
  5.         configuration.addMapper(BlogMapper.class);  
  6.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);  

              通过SqlSessionFactory获取SqlSession

[java] view plain copy
 print?
  1.         SqlSession session = sqlSessionFactory.openSession();  
  2.         try {  
  3.           BlogMapper mapper = session.getMapper(BlogMapper.class);  
  4.           Blog blog = mapper.selectBlog(101);  
  5.         } finally {  
  6.           session.close();  
  7.         }  

  • forEach应用

             forEach按照官方支持对单一数组和集合进行遍历,以下是对单一数组进行遍历的示例,集合参数其实是类似的

[html] view plain copy
 print?
  1. <delete id="deleteFile" parameterType="HashMap">  
  2.     delete  
  3.     From tbl_File  
  4.     Where themeKey = #{themeKey}  
  5.     <trim suffixOverrides="and">  
  6.       <if test="arrFileUrl != null and arrFileUrl != '' ">  
  7.           And fileUrl in  
  8.           <foreach item="item" index="index" collection="arrFileUrl"  
  9.               open="(" separator="," close=")">  
  10.                 #{item}  
  11.           </foreach>              
  12.       </if>  
  13.     </trim>  
  14. </delete>  

              调用方法:

[java] view plain copy
 print?
  1. HashMap<String, Object> argMap = new HashMap<String, Object>();         
  2. argMap.put("themeKey", themeKey);   
  3. /*arrFileUrl 是一个字符串数组*/        
  4. argMap.put("arrFileUrl", arrFileUrl);  
  5.   
  6. deleteFile(HashMap<String, Object> argMap);  

              foreach支持遍历list,map,array 三种类型,因此利用foreach以上特性实现批量插入数据功能。

[html] view plain copy
 print?
  1.     <insert id="addTrainRecordBatch" useGeneratedKeys="true" parameterType="java.util.List">    
  2.         <selectKey resultType="long" keyProperty="id" order="AFTER">    
  3.             SELECT    
  4.             LAST_INSERT_ID()    
  5.         </selectKey>    
  6.   
  7.         insert into t_train_record (add_time,emp_id,activity_id,flag)     
  8.         values    
  9.   
  10.         <foreach collection="list" item="item" index="index" separator="," >    
  11.             (#{item.addTime},#{item.empId},#{item.activityId},#{item.flag})    
  12.         </foreach>    
  13.     </insert>    

  • collection应用

[html] view plain copy
 print?
  1.     <resultMap id="Guide" type="Guide">  
  2.         <id column="spaguideKey"         property="guideKey"/>  
  3.         <result column="GUIDENAME"       property="guideName"/>  
  4.         <result column="GRADE"           property="grade"/>  
  5.         <result column="gradeName"       property="gradeName"/>  
  6.         <result column="SUBJECT"         property="subject"/>  
  7.         <result column="subjectName"             property="subjectName"/>  
  8.         <result column="CREATECODE"          property="createCode"/>  
  9.         <result column="realName"        property="realName"/>  
  10.         <result column="CREATETIME"          property="createTime"/>  
  11.         <result column="ISVALID"         property="isValid"/>  
  12.         <result column="ISREVIEW"        property="isReview"/>  
  13.         <result column="CONTENT"         property="content"/>  
  14.           
  15.                 <collection  property="guideVideoList"  ofType="GuideVideo">  
  16.             <id column="spavideokey"     property="videoKey"/>  
  17.             <result column="videoName"   property="videoName"/>  
  18.             <result column="videoFileUrl"    property="fileUrl"/>          
  19.                 </collection>   
  20.                 <collection  property="guideArchiveList" ofType="GuideArchive">  
  21.             <id column="SPAARCHIVESKEY"  property="archiveKey"/>  
  22.             <result column="archiveName"     property="archiveName"/>  
  23.             <result column="archiveFileUrl" property="fileUrl"/>          
  24.                 </collection>  
  25.     </resultMap>  
  26.   
  27.   
  28.     <select id="getGuide" parameterType="Guide" resultMap="Guide">  
  29.         Select   
  30.             sg.SPAGUIDEKEY,  
  31.             GUIDENAME,  
  32.             CREATETIME,  
  33.             CONTENT,  
  34.             grade,  
  35.             gradeName,  
  36.             subject,  
  37.             subjectName,  
  38.             CREATECODE,  
  39.             realName,          
  40.             spavideokey,  
  41.             videoName,  
  42.             videoFileName,  
  43.             videoFileUrl,            
  44.             SPAARCHIVESKEY,  
  45.             ARCHIVENAME,  
  46.             archiveFileName,  
  47.             archiveFileUrl   
  48.         from vw_spa_guide sg  
  49.         left join vw_spa_guide_video sgv on sgv.spaguidekey = sg.spaguidekey  
  50.         left join vw_spa_guide_archive sga on sga.spaguidekey = sg.spaguidekey  
  51.     </select>  


  • Mybatis 嵌套查询

[html] view plain copy
 print?
  1. <resultMap type="User" id="userResultMap">  
  2.     <id property="id" column="user_id"  />  
  3.     <result property="userName" column="user_userName"  />  
  4.     <result property="userAge" column="user_userAge"  />  
  5.     <result property="userAddress" column="user_userAddress"  />  
  6. </resultMap>  
  7.   
  8. <resultMap id="articleResultMap" type="Article">  
  9.     <id property="id" column="article_id" />  
  10.     <result property="title" column="article_title" />  
  11.     <result property="content" column="article_content" />  
  12.     <association property="user" javaType="User" resultMap="userResultMap"/>    
  13. </resultMap>  
  14.   
  15. <select id="getUserArticles" parameterType="int" resultMap="articleResultMap">  
  16.    select user.id user_id,user.userName user_userName,user.userAddress user_userAddress,  
  17.    article.id article_id,article.title article_title,article.content article_content   
  18.    from user,article   
  19.    where user.id=article.userid and user.id=#{id}  
  20. </select>  

        借用别人的例子来说明。

  • mybatis 自定义主键

[html] view plain copy
 print?
  1. <insert id="insertTest" parameterType="Test">   
  2.     <selectKey  keyProperty="testKey" order="BEFORE" resultType="String">  
  3.           SELECT  SEQ_TST_TEST.nextval   
  4.           FROM DUAL  
  5.      </selectKey>  
  6.            
  7.     insert into TST_TEST(  
  8.         TESTKEY,  
  9.         TESTNAME  
  10.     )values(  
  11.         #{testKey},  
  12.         #{testName}  
  13.     )  
  14. </insert>  

         mybatis 相对于Oracle的自增长先进行查询读取下一个主键,oracle不支持useGeneratedKeys,然后再进行插入操作。相对于其他数据库可以采用如下方式


[html] view plain copy
 print?
  1. <insert id="insertTest" parameterType="Test" useGeneratedKeys="true" keyProperty="testKey">    
  2.     insert into Test(testKey, testName)    
  3.     values(#{testKey},#{testName})    
  4. </insert>    

  • mybatis复用语句块

[html] view plain copy
 print?
  1. <!--定义可重用的SQL代码段-->    
  2. <sql id="multiplexSql">testKey, testName</sql>    
  3.     
  4. <select id="getTest" parameterType="int" resultType="hashmap">    
  5.     select   
  6.         <include refid="multiplexSql"/>   
  7.     from Blog   
  8.     where id = #{testKey}    
  9. </select>    

  • Mybatis执行函数,返回结果集

[html] view plain copy
 print?
  1. <select id="getSelfStatisticData" parameterType="HashMap" statementType="CALLABLE" >  
  2.         {#{result,mode=OUT,jdbcType=CURSORresultMap=SelfStatisticData} = call PKG_RRT_SelfStatics.Fn_GetSelfStatData(#{userCode,jdbcType=VARCHAR,mode=IN})}         
  3. </select>       

                 Java调用的代码

[plain] view plain copy
 print?
  1. public interface SelfStatisticDataDao {  
  2. blic List<SelfStatisticData> getSelfStatisticData(Map<String, Object> statMap);  
  3. }  
                 statMap 中的键值对对应着Fn_GetSelfStatData()函数的参数,键名与参数名保持完全一致,区分大小写。
                 SelfStatisticData定义的实体保持与结果集的字段一致。
  • Mybatis执行没有返回值的存储过程

[html] view plain copy
 print?
  1. <select id="insertGuideIntegral" parameterType="HashMap" statementType="CALLABLE" >  
  2.      {  
  3.          call PKG_Center_Integral_guide.Pro_SyncGuideIntegral(  
  4.              #{userCode,jdbcType=VARCHAR,mode=IN},  
  5.              #{integralKey,jdbcType=VARCHAR,mode=IN},  
  6.              #{gradeKey,jdbcType=VARCHAR,mode=IN},  
  7.              #{subjectKey,jdbcType=VARCHAR,mode=IN}  
  8.          )  
  9.      }  
  10. </select>  

  •  Mybatis执行带有返回两个游标结果集和输出参数

[html] view plain copy
 print?
  1. <resultMap type="IntegralResult" id="integralResult">    
  2.     <result column="integralKey" property="integralKey"/>    
  3.     <result column="integralName" property="integralName"/>    
  4. </resultMap>    
  5.   
  6. <resultMap type="GuideIntegralResult" id="guideIntegralResult">    
  7.     <result column="guideIntegralKey" property="guideIntegralKey"/>    
  8.     <result column="guideIntegralName" property="guideIntegralName"/>    
  9. </resultMap>    
  10.   
  11. <select id="get" parameterType="java.util.Map" statementType="CALLABLE"  resultMap="integralResult, guideIntegralResult">    
  12.     {  
  13.         call PKG_Center_Integral_guide.Pro_GuideIntegral(    
  14.             #{userCode,jdbcType=VARCHAR,mode=IN},  
  15.             #{subjectKey,jdbcType=VARCHAR,mode=IN},  
  16.             #{userName, mode=OUTjdbcType=String}  
  17.         )  
  18.     }    
  19. </select>   

  • Mybatis 支持结构体类型

[html] view plain copy
 print?
  1. #{middleInitial, mode=OUTjdbcType=STRUCTjdbcTypeName=MY_TYPEresultMap=departmentResultMap}  

            MY_TYPE为数据库中自定义的结构体
  • 定义输入输出小数点

[plain] view plain copy
 print?
  1. #{height,javaType=double,jdbcType=NUMERIC,numericScale=2}    

  • 使用association进行复杂映射

[html] view plain copy
 print?
  1.         <resultMap type="Blog" id="Blog_result">          
  2.             <id column="id" property="id" />    
  3.             <result column="title" property="title"/>    
  4.             
  5.             <!-- 映射关联的对象 -->    
  6.             <association property="author" javaType="Author">    
  7.                 <id column="author_id" property="id"/>    
  8.                 <result column="username" property="username"/>    
  9.                 <result column="password" property="password"/>    
  10.                 <result column="email" property="email"/>    
  11.                 <result column="bio" property="bio"/>    
  12.             </association>              
  13.          </resultMap>    
  14.   
  15.   
  16.         <select id="selectBlog_by_id" parameterType="int" resultMap="Blog_result">    
  17.             select    
  18.                 b.id,    
  19.                 b.title,    
  20.                 b.author_id,    
  21.                 a.id,    
  22.                 a.username,    
  23.                 a.password,    
  24.                 a.email,    
  25.                 a.bio    
  26.             from  Blog b   
  27.             left join Author a  on  b.author_id = a.id    
  28.             where  b.id = #{id}    
  29.         </select>  

  • 定义输入输出和指定游标结果集

[html] view plain copy
 print?
  1. #{  
  2.     department,    
  3.     mode=OUT,    
  4.     jdbcType=CURSOR,    
  5.     javaType=ResultSet,    
  6.     resultMap=departmentResultMap  
  7. }    

             mode属性允许你指定IN,OUT或INOUT参数。如果mode为OUT(或INOUT),而且jdbcType为CURSOR(也就是Oracle的REFCURSOR),你必须指定一个resultMap来映射结果集到参数类型。


原创粉丝点击