zoukankan      html  css  js  c++  java
  • Spring Boot2从入门到实战:整合通用Mapper简化单表操作

    数据库访问是web应用必不可少的部分。现今最常用的数据库ORM框架有Hibernate与Mybatis,Hibernate貌似在传统IT企业用的较多,而Mybatis则在互联网企业应用较多。通用Mapper(https://github.com/abel533/Mapper) 是一个基于Mybatis,将单表的增删改查通过通用方法实现,来减少SQL编写的开源框架,且也有对应开源的mapper-spring-boot-starter提供。我们在此基础上加了一些定制化的内容,以便达到更大程度的复用。

    框架源码地址:https://github.com/ronwxy/base-spring-boot (持续更新完善中,欢迎follow,star)
    Demo源码地址:https://github.com/ronwxy/springboot-demos/tree/master/springboot-tkmapper

    在开源mapper-spring-boot-starter的基础上,增加了如下内容:

    1. 针对MySQL数据库与PostgreSQL数据库添加了一些Java类型与数据库类型的转换处理类,如将List、Map类型与MySQL数据库的json类型进行转换处理
    2. 对Domain、Mapper、Service、Controller各层进行了封装,将基本的增删改查功能在各层通用化
    3. 提供了基于druid连接池的自动配置
    4. 其它一些调整,如默认映射复杂类型属性(主要是List、Map类型,其它自定义类型需要自定义转换处理类),将枚举作为简单类型处理
    5. 提供了一个parent项目,将一些常用的框架进行集成,实际项目可继承parent简化依赖配置(持续更新完善)

    该框架可用于实际基于springboot的项目,只需简单配置数据源,即可引入druid连接池及通用mapper的功能,以及各层基本的增删改查方法。

    如何使用?
    下文给出使用步骤,可参考示例:https://github.com/ronwxy/springboot-demos/tree/master/springboot-tkmapper

    1. 框架Maven部署安装

    下载框架源码后,在项目根路径下执行mvn clean install可安装到本地maven库。如果需要共享,且搭了Nexus私服,则在根路径pom.xml文件中添加distributionManagement配置,指定Nexus仓库分发地址,使用mvn clean deploy安装到远程maven仓库,如

    <distributionManagement>
         <repository>
             <id>nexus-releases</id>
             <url>
                 http://ip:port/repository/maven-releases/
             </url>
         </repository>
         <snapshotRepository>
             <id>nexus-snapshots</id>
             <url>
                 http://ip:port/repository/maven-snapshots/
             </url>
         </snapshotRepository>
     </distributionManagement>

    上述指定的repository需要在maven的全部配置文件settings.xml中有对应账号配置(id需要一一对应),如 

     <servers>
       <server>
         <id>nexus-snapshots</id>
         <username>admin</username>
         <password>xxx</password>
       </server>
    <server>
         <id>nexus-releases</id>
         <username>admin</username>
         <password>xxx</password>
       </server>
     </servers>

    2. pom.xml配置

    项目中引入该数据库框架有三种方式:

    1. 直接引入 cn.jboost.springboot:tkmapper-spring-boot-starter(没有连接池)
    2. 直接引入 cn.jboost.springboot:druid-spring-boot-starter(druid连接池支持)
    3. 项目继承 cn.jboost.springboot:spring-boot-parent(使用的是druid连接池)

    三种方式的pom.xml配置如下

    #第一种方式
    <dependency>
       <groupId>cn.jboost.springboot</groupId>
       <artifactId>tkmapper-spring-boot-starter</artifactId>
       <version>1.2-SNAPSHOT</version>
    </dependency>
    
    #第二种方式
    <dependency>
       <groupId>cn.jboost.springboot</groupId>
       <artifactId>druid-spring-boot-starter</artifactId>
       <version>1.2-SNAPSHOT</version>
    </dependency>
    
    #第三种方式
    <parent>
       <groupId>cn.jboost.springboot</groupId>
       <artifactId>spring-boot-parent</artifactId>
       <version>1.2-SNAPSHOT</version>
       <relativePath/> <!-- lookup parent from repository -->
    </parent>

    根据情况引入mysql或postgresql的驱动依赖(其它数据库暂未做类型转换支持,未作测试)

    3. 配置数据源

    如果使用druid连接池,则在application.yml配置文件中,加入如下数据源配置(推荐)

    spring:
      datasource:
        druid:
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
          username: root
          password:
          # 自定义配置
          initialSize: 2  # 初始化大小
          minIdle: 1   # 最小连接
          maxActive: 5 # 最大连接
          druidServletSettings:
            allow: 127.0.0.1
            deny:
            loginUsername: admin
            loginPassword: Passw0rd
            resetEnable: true
          druidFilterSettings:
            exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
          maxWait: 60000   # 配置获取连接等待超时的时间
          timeBetweenEvictionRunsMillis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
          minEvictableIdleTimeMillis: 300000 # 配置一个连接在池中最小生存的时间,单位是毫秒
          validationQuery: SELECT 'x'
          testWhileIdle: true
          testOnBorrow: false
          testOnReturn: false
          poolPreparedStatements: true # 打开PSCache,并且指定每个连接上PSCache的大小
          maxPoolPreparedStatementPerConnectionSize: 20
          filters: stat #,wall(添加wall代码里不能直接拼接sql,druid有sql注入校验) # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
          connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
          useGlobalDataSourceStat: true # 合并多个DruidDataSource的监控数据

    如果不使用连接池,则配置相对简单,如下 

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
        username: root
        password:
        driver-class-name: com.mysql.jdbc.Driver

    4. 定义相应domain,mapper,service,controller各层对象 

    以demo为例(demo数据库脚本见resources/schema.sql),domain定义一个User类,

    @Table(name = "user")
    @Getter
    @Setter
    @ToString
    public class User extends AutoIncrementKeyBaseDomain<Integer> {
        private String name;
        @ColumnType(jdbcType = JdbcType.CHAR)
        private Gender gender;
        private List<String> favor;
        private Map<String, String> address;
    
        public enum Gender{
            M,
            F
        }
    }

    需要添加@Table注解指定数据库表名,可通过继承AutoIncrementKeyBaseDomain来实现自增主键,或UUIDKeyBaseDomain来实现UUID主键,如果自定义其它类型主键,则继承BaseDomain。 

    该框架Service层通用方法实现BaseService只支持单列主键,不支持组合主键(也不建议使用组合主键)

    框架默认对List、Map等复杂类型属性会映射到mysql的json类型或postgresql的jsonb类型,如果某个属性不需要映射,可添加@Transient注解;枚举类型需添加@ColumnType指定jdbcType。

    dao层定义UserMapper

    @Repository
    public interface UserMapper extends BaseMapper<User> {
    }

    BaseMapper默认实现了单表的增删改查及批量插入等功能,如需定义复杂查询,可在该接口中定义,然后通过mapper xml文件编写实现。 

    service层定义 UserService,继承了BaseService的通用功能(具体可查看源码),同样可在该类中自定义方法

    @Service
    public class UserService extends BaseService<Integer, User> {
    
        @Transactional
        public void createWithTransaction(User user){
            create(user);
            //用于测试事务
            throw new RuntimeException("抛出异常,让前面的数据库操作回滚");
        }
    }

    controller层定义 UserController,继承了BaseController的通用接口(具体可查看源码) 

    @RestController
    @RequestMapping("/user")
    public class UserController extends BaseController<Integer, User> {
    }

    如上,只需要定义各层对应的接口或类,继承基础接口或类,便完成了用户基本的增删改查功能,不需要写一行具体的实现代码。 

    5. 测试、运行

    1. 示例中提供了两个新建用户的单元测试,参考SpringbootTkmapperApplicationTests

    2. 运行,在主类上直接运行,然后浏览器里打开 http://localhost:8080/user 则可列出单元测试中创建的用户(其它接口参考BaseController实现)

    6. 总结

    本文介绍框架基于tk.mybatis:mapper-spring-boot-starter做了一些自定义扩展,以更大程度地实现复用。可用于实际项目开发,使用过程中如果遇到问题,可关注公众号留言反馈。




    我的个人博客地址:http://blog.jboost.cn
    我的头条空间: https://www.toutiao.com/c/user/5833678517/#mid=1636101215791112
    我的github地址:https://github.com/ronwxy
    我的微信公众号:jboost-ksxy

    ————————————————————————————————————————

    微信公众号
    欢迎关注我的微信公众号,及时获取最新分享

  • 相关阅读:
    看net2.0头晕眼花,是不是该做个具体的程序呢
    安装SQLServer2000时,提示"以前的某个程序安装已在安装计算机上创建挂起的文件操作。运行安装程序之前必须重新启动计算机"
    刚装的WIN7,用了一下午,记一下备忘
    不同系统开启和关闭fso的方法(转)
    希腊字母以及发音
    meta 标签的作用
    电信禁止路由上网的最佳破解方法(转)
    安装系统
    网络工程师笔记
    GHOST操作
  • 原文地址:https://www.cnblogs.com/spec-dog/p/11080741.html
Copyright © 2011-2022 走看看