Mybatis-spring-boot-starter简介


Mybatis-spring-boot-starter简介

一、maven配置

 <dependency>
             <groupId>org.mybatis.spring.boot</groupId>
             <artifactId>mybatis-spring-boot-starter</artifactId>
             <version>2.2.0</version>
         </dependency>
 
         <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
             <optional>true</optional>
         </dependency>
 
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-jdbc</artifactId>
             <version>2.5.4</version>
         </dependency>
 
         <dependency>
             <groupId>com.microsoft.sqlserver</groupId>
             <artifactId>sqljdbc4</artifactId>
             <version>4.0</version>
         </dependency>

二、properties配置

 spring.datasource.username=sa
 spring.datasource.password=********
 spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=***
 spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
 
 mybatis.type-aliases-package=com.****.szxinterface.pojo.mapper
 mybatis.mapper-locations=classpath:mapper/*.xml
 mybatis.configuration.map-underscore-to-camel-case=true
 
 logging.root.level=debug #显示调试SQL语句

 

 @Mapper
 @Repository
 public interface MiningCarRunStatusMapper {
     List<MineCarRunStatus> findMiningCarRunStatusS(@Param("param") String Date);
 }
 <mapper namespace="com.dfmc.szxinterface.mapper.MiningCarRunStatusMapper">
     <select id="findMiningCarRunStatusS" parameterType="java.lang.String" resultType="com.dfmc.szxinterface.model.MineCarRunStatus">
        exec sg_interface_data_truck #{param}
     </select>
 </mapper>

 

三、mybatis-spring-boot-starter

1、简介

MyBatis-Spring-Boot-Starter类似一个中间件,链接Spring Boot和MyBatis,构建基于Spring Boot的MyBatis人应用程序。

MyBatis-Spring-Boot-Starter 当前版本是 2.1.2,发布于2020年3月10日

MyBatis-Spring-Boot-Starter是个集成包,因此对MyBatis、MyBatis-Spring和SpringBoot的jar包都存在依赖,如下所示:

MyBatis-Spring-Boot-Starter MyBatis-Spring Spring Boot Java
2.1 2.0 (need 2.0.2+ for enable all features) 2.1 or higher 8 or higher
1.3 1.3 1.5 6 or higher

2、安装

 <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.1.1</version>
 </dependency>

3、快速上手

众所周知,MyBatis的核心有两大组件:SqlSessionFactory 和 Mapper 接口。前者表示数据库链接,后者表示SQL映射。当我们基于Spring使用MyBatis的时候,也要保证在Spring环境中能存在着两大组件。

MyBatis-Spring-Boot-Starter 将会完成以下功能:

1、Autodetect an existing DataSource 自动发现存在的DataSource

2、Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean 利用SqlSessionFactoryBean创建并注册SqlSessionFactory

3、Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory 创建并注册SqlSessionTemplate

4、Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans 自动扫描Mappers,并注册到Spring上下文环境方便程序的注入使用

假设,我们有如下Mapper:

 @Mapper
 public interface CityMapper {
 
   @Select("SELECT * FROM CITY WHERE state = #{state}")
   City findByState(@Param("state") String state);
 
 }

你仅仅需要创建一个Spring Boot程序让Mapper注入即可:

 @SpringBootApplication
 public class SampleMybatisApplication implements CommandLineRunner {
 
   private final CityMapper cityMapper;
 
   public SampleMybatisApplication(CityMapper cityMapper) {
     this.cityMapper = cityMapper;
  }
 
   public static void main(String[] args) {
     SpringApplication.run(SampleMybatisApplication.class, args);
  }
 
   @Override
   public void run(String... args) throws Exception {
     System.out.println(this.cityMapper.findByState("CA"));
  }
 
 }

仅此而已,如上程序就是一个Spring Boot程序。

4、高级扫描

默认情况下,MyBatis-Spring-Boot-Starter会查找以@Mapper注解标记的映射器。

你需要给每个MyBatis映射器标识上@Mapper注解,但是这样非常的麻烦,这时可以使用@MapperScan注解来扫描包。

备注:关于@MapperScan注解更多的介绍,请移步这里:http://www.mybatis.cn/archives/862.html

需要提醒的是:如果MyBatis Spring Boot Starter在Spring的上下文中至少找到一个MapperFactoryBean,那么它将不会启动扫描过程,因此如果你想停止扫描,那么应该使用@Bean方法显式注册映射器。

标签: none

 

三、mybatis中文文档

 http://mybatis.org/mybatis-3/zh/dynamic_sql.html

1、动态sql语句

1.1、if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:

 <select id="findActiveBlogWithTitleLike"
      resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
   <if test="title != null">
    AND title like #{title}
   </if>
 </select>

这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。

如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。

 <select id="findActiveBlogLike"
      resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
   <if test="title != null">
    AND title like #{title}
   </if>
   <if test="author != null and author.name != null">
    AND author_name like #{author.name}
   </if>
 </select>

 

1.2、choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。

 <select id="findActiveBlogLike"
      resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
   <choose>
     <when test="title != null">
      AND title like #{title}
     </when>
     <when test="author != null and author.name != null">
      AND author_name like #{author.name}
     </when>
     <otherwise>
      AND featured = 1
     </otherwise>
   </choose>
 </select>

 

1.3、trim、where、set

前面几个例子已经方便地解决了一个臭名昭著的动态 SQL 问题。现在回到之前的 “if” 示例,这次我们将 “state = ‘ACTIVE’” 设置成动态条件,看看会发生什么。

 <select id="findActiveBlogLike"
      resultType="Blog">
  SELECT * FROM BLOG
  WHERE
   <if test="state != null">
    state = #{state}
   </if>
   <if test="title != null">
    AND title like #{title}
   </if>
   <if test="author != null and author.name != null">
    AND author_name like #{author.name}
   </if>
 </select>

如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:

 SELECT * FROM BLOG
 WHERE

这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:

 SELECT * FROM BLOG
 WHERE
 AND title like ‘someTitle’

这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。

MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:

 <select id="findActiveBlogLike"
      resultType="Blog">
  SELECT * FROM BLOG
   <where>
     <if test="state != null">
          state = #{state}
     </if>
     <if test="title != null">
        AND title like #{title}
     </if>
     <if test="author != null and author.name != null">
        AND author_name like #{author.name}
     </if>
   </where>
 </select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

 <trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
 </trim>

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

 <update id="updateAuthorIfNecessary">
  update Author
     <set>
       <if test="username != null">username=#{username},</if>
       <if test="password != null">password=#{password},</if>
       <if test="email != null">email=#{email},</if>
       <if test="bio != null">bio=#{bio}</if>
     </set>
  where id=#{id}
 </update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

来看看与 set 元素等价的自定义 trim 元素吧:

 <trim prefix="SET" suffixOverrides=",">
  ...
 </trim>

注意,我们覆盖了后缀值设置,并且自定义了前缀值。

1.4、foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:

 <select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
   <foreach item="item" index="index" collection="list"
       open="(" separator="," close=")">
        #{item}
   </foreach>
 </select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!

提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

至此,我们已经完成了与 XML 配置及映射文件相关的讨论。下一章将详细探讨 Java API,以便你能充分利用已经创建的映射配置。

1.5、script

要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素。比如:

     @Update({"<script>",
       "update Author",
       " <set>",
       "   <if test='username != null'>username=#{username},</if>",
       "   <if test='password != null'>password=#{password},</if>",
       "   <if test='email != null'>email=#{email},</if>",
       "   <if test='bio != null'>bio=#{bio}</if>",
       " </set>",
       "where id=#{id}",
       "</script>"})
     void updateAuthorValues(Author author);

1.6、bind

bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:

 <select id="selectBlogsLike" resultType="Blog">
   <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
 </select>

四、文档

 https://github.com/mybatis/spring-boot-starter

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM