当前位置:   article > 正文

SpringBoot2.x入门:使用MyBatis

springboot2.x mybatis pom

点击上方蓝字 ↑↑ Throwable文摘

关注公众号设置星标,不定时推送高质量原创文章

关注

前提

这篇文章是《SpringBoot2.x入门》专辑的「第8篇」文章,使用的SpringBoot版本为2.3.1.RELEASEJDK版本为1.8

SpringBoot项目引入MyBatis一般的套路是直接引入mybatis-spring-boot-starter或者使用基于MyBatis进行二次封装的框架例如MyBatis-Plus或者tk.mapper等,但是本文会使用一种更加原始的方式,单纯依赖org.mybatis:mybatisorg.mybatis:mybatis-springMyBatis的功能整合到SpringBoot中,Spring(Boot)使用的是「微内核架构」,任何第三方框架或者插件都可以按照本文的思路融合到该微内核中。

引入MyBatis依赖

编写本文的时候(2020-07-18org.mybatis:mybatis的最新版本是3.5.5,而org.mybatis:mybatis-spring的最新版本是2.0.5,在使用BOM管理SpringBoot版本的前提下,引入下面的依赖:

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6.     <groupId>org.springframework.boot</groupId>
  7.     <artifactId>spring-boot-starter-jdbc</artifactId>
  8. </dependency>
  9. <dependency>
  10.     <groupId>org.mybatis</groupId>
  11.     <artifactId>mybatis</artifactId>
  12.     <version>3.5.5</version>
  13. </dependency>
  14. <dependency>
  15.     <groupId>org.mybatis</groupId>
  16.     <artifactId>mybatis-spring</artifactId>
  17.     <version>2.0.5</version>
  18. </dependency>

注意的是低版本的MyBatis如果需要使用JDK8的日期时间API,需要额外引入mybatis-typehandlers-jsr310依赖,但是某个版本之后mybatis-typehandlers-jsr310中的类已经移植到org.mybatis:mybatis中作为内建类,可以放心使用JDK8的日期时间API。

添加MyBatis配置

MyBatis的核心模块是SqlSessionFactoryMapperScannerConfigurer。前者可以使用SqlSessionFactoryBean,功能是为每个SQL的执行提供SqlSession和加载全局配置或者SQL实现的XML文件,后者是一个BeanDefinitionRegistryPostProcessor实现,主要功能是主动通过配置的基础包(Base Package)中递归搜索Mapper接口(这个算是MyBatis独有的扫描阶段,「务必指定明确的扫描包,否则会因为效率太低导致启动阶段耗时增加」),并且把它们注册成MapperFactoryBean(简单理解为接口动态代理实现添加到方法缓存中,并且委托到IOC容器,此后可以直接注入Mapper接口),注意这个BeanFactoryPostProcessor的回调优先级极高,在自动装配@Autowired族注解或者@ConfigurationProperties属性绑定处理之前已经回调,「因此在处理MapperScannerConfigurer的属性配置时候绝对不能使用@Value或者自定义前缀属性Bean进行自动装配」,但是可以从Environment中直接获取。

这里添加一个自定义属性前缀mybatis,用于绑定配置文件中的属性到MyBatisProperties类中:

  1. @ConfigurationProperties(prefix = "mybatis")
  2. @Data
  3. public class MyBatisProperties {
  4.     private String configLocation;
  5.     private String mapperLocations;
  6.     private String mapperPackages;
  7.     private static final ResourcePatternResolver RESOLVER = new PathMatchingResourcePatternResolver();
  8.     /**
  9.      * 转化Mapper映射文件为Resource
  10.      */
  11.     public Resource[] getMapperResourceArray() {
  12.         if (!StringUtils.hasLength(mapperLocations)) {
  13.             return new Resource[0];
  14.         }
  15.         List<Resource> resources = new ArrayList<>();
  16.         String[] locations = StringUtils.commaDelimitedListToStringArray(mapperLocations);
  17.         for (String location : locations) {
  18.             try {
  19.                 resources.addAll(Arrays.asList(RESOLVER.getResources(location)));
  20.             } catch (IOException e) {
  21.                 throw new IllegalArgumentException(e);
  22.             }
  23.         }
  24.         return resources.toArray(new Resource[0]);
  25.     }
  26. }

接着添加一个MybatisAutoConfiguration用于配置SqlSessionFactory

  1. @Configuration
  2. @EnableConfigurationProperties(value = {MyBatisProperties.class})
  3. @ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
  4. @RequiredArgsConstructor
  5. public class MybatisAutoConfiguration {
  6.     private final MyBatisProperties myBatisProperties;
  7.     @Bean
  8.     public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
  9.         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  10.         bean.setDataSource(dataSource);
  11.         // 其实核心配置就是这两项,其他TypeHandlersPackage、TypeAliasesPackage等等自行斟酌是否需要添加
  12.         bean.setConfigLocation(new ClassPathResource(myBatisProperties.getConfigLocation()));
  13.         bean.setMapperLocations(myBatisProperties.getMapperResourceArray());
  14.         return bean;
  15.     }
  16.     /**
  17.      * 事务模板,用于编程式事务 - 可选配置
  18.      */
  19.     @Bean
  20.     @ConditionalOnMissingBean
  21.     public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager) {
  22.         return new TransactionTemplate(platformTransactionManager);
  23.     }
  24.     /**
  25.      * 数据源事务管理器 - 可选配置
  26.      */
  27.     @Bean
  28.     @ConditionalOnMissingBean
  29.     public PlatformTransactionManager platformTransactionManager(DataSource dataSource) {
  30.         return new DataSourceTransactionManager(dataSource);
  31.     }
  32. }

一般情况下,启用事务需要定义PlatformTransactionManager的实现,而TransactionTemplate适用于编程式事务(和声明式事务@Transactional区别,编程式更加灵活)。上面的配置类中只使用了两个属性,而mybatis.mapperPackages将用于MapperScannerConfigurer的加载上。添加MapperScannerRegistrarConfiguration如下:

  1. @Configuration
  2. public class MapperScannerRegistrarConfiguration {
  3.     public static class AutoConfiguredMapperScannerRegistrar implements
  4.             BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
  5.         private Environment environment;
  6.         private BeanFactory beanFactory;
  7.         @Override
  8.         public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
  9.             this.beanFactory = beanFactory;
  10.         }
  11.         @Override
  12.         public void setEnvironment(@NonNull Environment environment) {
  13.             this.environment = environment;
  14.         }
  15.         @Override
  16.         public void registerBeanDefinitions(@NonNull AnnotationMetadata importingClassMetadata,
  17.                                             @NonNull BeanDefinitionRegistry registry) {
  18.             BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
  19.             builder.addPropertyValue("processPropertyPlaceHolders"true);
  20.             StringJoiner joiner = new StringJoiner(ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
  21.             // 这里使用了${mybatis.mapperPackages},否则会使用AutoConfigurationPackages.get(this.beanFactory)获取项目中自定义配置的包
  22.             String mapperPackages = environment.getProperty("mybatis.mapperPackages");
  23.             if (null != mapperPackages) {
  24.                 String[] stringArray = StringUtils.commaDelimitedListToStringArray(mapperPackages);
  25.                 for (String pkg : stringArray) {
  26.                     joiner.add(pkg);
  27.                 }
  28.             } else {
  29.                 List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
  30.                 for (String pkg : packages) {
  31.                     joiner.add(pkg);
  32.                 }
  33.             }
  34.             builder.addPropertyValue("basePackage", joiner.toString());
  35.             BeanWrapper beanWrapper = new BeanWrapperImpl(MapperScannerConfigurer.class);
  36.             Stream.of(beanWrapper.getPropertyDescriptors())
  37.                     .filter(x -> "lazyInitialization".equals(x.getName())).findAny()
  38.                     .ifPresent(x -> builder.addPropertyValue("lazyInitialization",
  39.                             "${mybatis.lazyInitialization:false}"));
  40.             registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
  41.         }
  42.     }
  43.     @Configuration
  44.     @Import(AutoConfiguredMapperScannerRegistrar.class)
  45.     @ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
  46.     public static class MapperScannerRegistrarNotFoundConfiguration {
  47.     }
  48. }

到此基本的配置Bean已经定义完毕,接着需要添加配置项。一般一个项目的MyBatis配置是相对固定的,可以直接添加在主配置文件application.properties中:

  1. server.port=9098
  2. spring.application.name=ch8-mybatis
  3. mybatis.configLocation=mybatis-config.xml
  4. mybatis.mapperLocations=classpath:mappings/base,classpath:mappings/ext
  5. mybatis.mapperPackages=club.throwable.ch8.repository.mapper,club.throwable.ch8.repository

个人喜欢在resource/mappings目录下定义baseext两个目录,base目录用于存在MyBatis生成器生成的XML文件,这样就能在后续添加了表字段之后直接重新生成和覆盖base目录下对应的XML文件即可。同理,在项目的源码包下建repository/mapper,然后Mapper类直接存放在repository/mapper目录,DAO类存放在repository目录,MyBatis生成器生成的Mapper类可以直接覆盖repository/mapper目录中对应的类。

resources目录下添加一个MyBatis的全局配置文件mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4.     <settings>
  5.         <!--下划线转驼峰-->
  6.         <setting name="mapUnderscoreToCamelCase" value="true"/>
  7.         <!--未知列映射忽略-->
  8.         <setting name="autoMappingUnknownColumnBehavior" value="NONE"/>
  9.     </settings>
  10. </configuration>

项目目前的基本结构如下:

使用Mybatis

为了简单起见,这里使用h2内存数据库进行演示。添加h2的依赖:

  1. <dependency>
  2.     <groupId>com.h2database</groupId>
  3.     <artifactId>h2</artifactId>
  4.     <version>1.4.200</version>
  5. </dependency>

resources目录下添加一个schema.sqldata.sql

  1. // resources/schema.sql
  2. drop table if exists customer;
  3. create table customer
  4. (
  5.     id            bigint generated by default as identity,
  6.     customer_name varchar(32),
  7.     age           int,
  8.     create_time   timestamp default current_timestamp,
  9.     edit_time     timestamp default current_timestamp,
  10.     primary key (id)
  11. );
  12. // resources/data.sql
  13. INSERT INTO customer(customer_name,age) VALUES ('doge'22);
  14. INSERT INTO customer(customer_name,age) VALUES ('throwable'23);

添加对应的实体类club.throwable.ch8.entity.Customer

  1. @Data
  2. public class Customer {
  3.     private Long id;
  4.     private String customerName;
  5.     private Integer age;
  6.     private LocalDateTime createTime;
  7.     private LocalDateTime editTime;
  8. }

添加MapperDAO类:

  1. // club.throwable.ch8.repository.mapper.CustomerMapper
  2. public interface CustomerMapper {
  3. }
  4. // club.throwable.ch8.repository.CustomerDao
  5. public interface CustomerDao extends CustomerMapper {
  6.     Customer queryByName(@Param("customerName") String customerName);
  7. }

添加XML文件resource/mappings/base/BaseCustomerMapper.xmlresource/mappings/base/ExtCustomerMapper.xml

  1. // BaseCustomerMapper.xml
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="club.throwable.ch8.repository.mapper.CustomerMapper">
  5.     <resultMap id="BaseResultMap" type="club.throwable.ch8.entity.Customer">
  6.         <id column="id" jdbcType="BIGINT" property="id"/>
  7.         <result column="customer_name" jdbcType="VARCHAR" property="customerName"/>
  8.         <result column="age" jdbcType="INTEGER" property="age"/>
  9.         <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
  10.         <result column="edit_time" jdbcType="TIMESTAMP" property="editTime"/>
  11.     </resultMap>
  12. </mapper>
  13. // ExtCustomerMapper.xml
  14. <?xml version="1.0" encoding="UTF-8"?>
  15. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  16. <mapper namespace="club.throwable.ch8.repository.CustomerDao">
  17.     <resultMap id="BaseResultMap" type="club.throwable.ch8.entity.Customer"
  18.                extends="club.throwable.ch8.repository.mapper.CustomerMapper.BaseResultMap">
  19.     </resultMap>
  20.     <select id="queryByName" resultMap="BaseResultMap">
  21.         SELECT *
  22.         FROM customer
  23.         WHERE customer_name = #{customerName}
  24.     </select>
  25. </mapper>

细心的伙伴会发现,DAO和Mapper类是继承关系,而ext和base下对应的Mapper文件中的BaseResultMap也是继承关系

配置文件中增加h2数据源的配置:

  1. // application.properties
  2. spring.datasource.url=jdbc:h2:mem:db_customer;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE
  3. spring.datasource.username=root
  4. spring.datasource.password=123456
  5. spring.datasource.driver-class-name=org.h2.Driver
  6. spring.h2.console.enabled=true
  7. spring.h2.console.path=/h2-console
  8. spring.h2.console.settings.web-allow-others=true
  9. spring.datasource.schema=classpath:schema.sql
  10. spring.datasource.data=classpath:data.sql

添加一个启动类进行验证:

  1. public class Ch8Application implements CommandLineRunner {
  2.     @Autowired
  3.     private CustomerDao customerDao;
  4.     @Autowired
  5.     private ObjectMapper objectMapper;
  6.     public static void main(String[] args) {
  7.         SpringApplication.run(Ch8Application.class, args);
  8.     }
  9.     @Override
  10.     public void run(String... args) throws Exception {
  11.         Customer customer = customerDao.queryByName("doge");
  12.         log.info("Query [name=doge],result:{}", objectMapper.writeValueAsString(customer));
  13.         customer = customerDao.queryByName("throwable");
  14.         log.info("Query [name=throwable],result:{}", objectMapper.writeValueAsString(customer));
  15.     }
  16. }

执行结果如下:

使用Mybatis生成器生成Mapper文件

有些时候为了提高开发效率,更倾向于使用生成器去预生成一些已经具备简单CRUD方法的Mapper文件,这个时候可以使用mybatis-generator-core。编写本文的时候(2020-07-18mybatis-generator-core的最新版本为1.4.0mybatis-generator-core可以通过编程式使用或者Maven插件形式使用。

这里仅仅简单演示一下Maven插件形式下使用mybatis-generator-core的方式,关于mybatis-generator-core后面会有一篇数万字的文章详细介绍此生成器的使用方式和配置项的细节。在项目的resources目录下添加一个generatorConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3.         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4.         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6.     <context id="H2Tables" targetRuntime="MyBatis3">
  7.         <property name="autoDelimitKeywords" value="true"/>
  8.         <property name="javaFileEncoding" value="UTF-8"/>
  9.         <property name="beginningDelimiter" value="`"/>
  10.         <property name="endingDelimiter" value="`"/>
  11.         <commentGenerator>
  12.             <property name="suppressDate" value="true"/>
  13.             <!-- 是否去除自动生成的注释 true:是 :false:否 -->
  14.             <property name="suppressAllComments" value="true"/>
  15.             <property name="suppressDate" value="true"/>
  16.         </commentGenerator>
  17.         <jdbcConnection driverClass="org.h2.Driver"
  18.                         connectionURL="jdbc:h2:mem:db_customer;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE"
  19.                         userId="root"
  20.                         password="123456"/>
  21.         <javaTypeResolver>
  22.             <property name="forceBigDecimals" value="false"/>
  23.         </javaTypeResolver>
  24.         <!-- 生成模型的包名和位置(实体类)-->
  25.         <javaModelGenerator targetPackage="club.throwable.ch8.entity"
  26.                             targetProject="src/main/java">
  27.             <property name="enableSubPackages" value="true"/>
  28.             <property name="trimStrings" value="false"/>
  29.         </javaModelGenerator>
  30.         <!-- 生成映射XML文件的包名和位置-->
  31.         <sqlMapGenerator targetPackage="mappings.base"
  32.                          targetProject="src/main/resources">
  33.             <property name="enableSubPackages" value="true"/>
  34.         </sqlMapGenerator>
  35.         <!-- 生成DAO的包名和位置-->
  36.         <javaClientGenerator type="XMLMAPPER"
  37.                              targetPackage="club.throwable.ch8.repository.mapper"
  38.                              targetProject="src/main/java">
  39.             <property name="enableSubPackages" value="true"/>
  40.         </javaClientGenerator>
  41.         <table tableName="customer"
  42.                enableCountByExample="false"
  43.                enableUpdateByExample="false"
  44.                enableDeleteByExample="false"
  45.                enableSelectByExample="false">
  46.         </table>
  47.     </context>
  48. </generatorConfiguration>

然后再项目的POM文件添加一个Maven插件:

  1. <plugins>
  2.     <plugin>
  3.         <groupId>org.mybatis.generator</groupId>
  4.         <artifactId>mybatis-generator-maven-plugin</artifactId>
  5.         <version>1.4.0</version>
  6.         <executions>
  7.             <execution>
  8.                 <id>Generate MyBatis Artifacts</id>
  9.                 <goals>
  10.                     <goal>generate</goal>
  11.                 </goals>
  12.             </execution>
  13.         </executions>
  14.         <configuration>
  15.             <jdbcURL>jdbc:h2:mem:db_customer;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE</jdbcURL>
  16.             <jdbcDriver>org.h2.Driver</jdbcDriver>
  17.             <jdbcUserId>root</jdbcUserId>
  18.             <jdbcPassword>123456</jdbcPassword>
  19.             <sqlScript>${basedir}/src/main/resources/schema.sql</sqlScript>
  20.         </configuration>
  21.         <dependencies>
  22.             <dependency>
  23.                 <groupId>com.h2database</groupId>
  24.                 <artifactId>h2</artifactId>
  25.                 <version>1.4.200</version>
  26.             </dependency>
  27.         </dependencies>
  28.     </plugin>
  29. </plugins>

笔者发现这里必须要在插件的配置中重新定义数据库连接属性和schema.sql,因为插件跑的时候无法使用项目中已经启动的h2实例,具体原因未知。

配置完毕之后,执行Maven命令:

mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate -X

然后resource/mappings/base目录下新增了一个带有基本CRUD方法实现的CustomerMapper.xml,同时CustoemrMapper接口和Customer实体也被重新覆盖生成了。

这里把前面手动编写的BaseCustomerMapper.xml注释掉,预防冲突。另外,CustomerMapper.xml的insertSelective标签需要加上keyColumn="id" keyProperty="id" useGeneratedKeys="true"属性,用于实体insert后的主键回写。

最后,修改并重启启动一下Ch8Application验证结果:

小结

这篇文章相对详细地介绍了SpringBoot项目如何使用MyBatis,如果需要连接MySQL或者其他数据库,只需要修改数据源配置和MyBatis生成器的配置文件即可,其他配置类和项目骨架可以直接复用。

本文demo仓库:

  • Github:https://github.com/zjcscut/spring-boot-guide/tree/master/ch8-mybatis

(本文完 c-2-d e-a-20200719 封面来自《秒速五厘米》)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/498232
推荐阅读
相关标签
  

闽ICP备14008679号