乐趣区

优雅写代码系统bootmybatispagehelpermybatisplusdruid教你优雅写代码

[TOC]

springboot 交融了很多插件。springboot 相比 spring 来说有一下有点

  • 主动配置:针对很多 spring 的应用程序,springboot 提供了很多主动配置
  • 起步依赖:通知 springboot 你须要什么,他就会引入须要的库
  • 命令行界面:springboot 的可选个性
  • Autuator: 监控 springboot 我的项目的运行状况

spring 根本搭建

  • springboot 的配置很简略。在 pom 中继承 springboot 的 pom . 而后依赖一下 pom 就能够继承所需的 jar 了

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
</parent>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  • 出了 jar 外。咱们 pom 中配置一个插件就行了

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

整合 mybatis

【详见 feature/0002/spring-mybatis 分支】

  • 之前咱们梳理过 mybatis 的运行机制及留神点。javaweb 的开发时离不开 spring 的。一个残缺的框架是离不开 spirng 的。所以 spring 整合 mybatis 势在必行。咱们上面实现如何在 spring 下交融 mybatis 及其优良的一些插件搭建架构

pom 配置

  • 咱们在 springboot 我的项目的 pom 中持续增加咱们 mybatis 的 jar 就实现了第一步。
  • 一个是 mybatis 与 spring 的整合 jar。开启 springboot 加载 mybatis 我的项目
  • 一个是 spring 的 aopjar 包。次要是实现 mybatis 的事务问题
  • 一个是 mysql 的 jar 包。这里次要看你本人的需要。如果你的我的项目中应用 oracle 那么久退出 oracle 的坐标就行了
  • druid 是治理数据的数据源

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

mybatis 配置

  • 下面的 pom 设置曾经筹备了 mybatis 开发阶段的根本 jar。有了上述的包就能够搭建 mybatis . 失常咱们在咱们的 springboot 我的项目中配置一个 bean 配置的类 MybatisConfig

设置数据源


@Bean
@ConfigurationProperties("spring.datasource")
public DataSource primaryDataSource() {
    // 这里为了演示,临时写死。实际上是能够通过 autoConfigure 拆卸参数的
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUsername("root");
    dataSource.setPassword("123456");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://192.168.44.130:3306/others?useUnicode=true&amp;characterEncoding=utf8");
    return dataSource;
}
  • 在 springboot 中咱们只须要在办法上增加 Bean 注解,就相当于咱们在 spring 的 xml 中配置的 bean 标签。在 java 代码中咱们能够进行咱们业务解决。集体了解感觉更加的可控。因为咱们应用的 mysql。所以这里咱们简略的应用 druid 的数据源

设置 sqlsessionfactory


@Bean
public SqlSessionFactory primarySqlSessionFactory() {
    SqlSessionFactory factory = null;
    try {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(primaryDataSource());
        sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/com/github/zxhtom.**./*.xml"));
        factory = sqlSessionFactoryBean.getObject();} catch (Exception e) {e.printStackTrace();
    }
    return factory;
}
  • 在 mybatis 中 sqlsesson 是咱们操作数据库最间接的 java 类。治理 sqlsession 就是下面的 sqlsessionFactory。所以咱们配置它也是必须的。因为和 spring 整合。Mybatis 的 SqlsessionFactory 交由给 spring 的 SqlsessionfactoryBean 治理。所以咱们先构建 SqlSessionFactoryBean。而后配置必须的数据源、Configuration、mybatis 的 xml 门路等等信息
  • SqlSessionFactoryBean 设置出了 spring 的 FactoryBean 属性意外。最重要的是能够设置 Mybatis 的 sqlsessionfactory 的属性。下面咱们只是简略的设置了。前期能够依据架构的需要进行一直的欠缺。
  • 能够设置插件、缓存、别名、映射处理器、事务、环境等等所有 mybatis 的配置

设置扫描


@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setSqlSessionFactory(primarySqlSessionFactory());
    // 每张表对应的 *.java,interface 类型的 Java 文件
    mapperScannerConfigurer.setBasePackage("com.github.zxhtom.**.mapper");
    return mapperScannerConfigurer;
}
  • springboot 中咱们的 mapper 接口也是交由 spring 来扫描的。之前 mybatis 程序咱们是一个一个手动退出的。spring 的个性能够间接扫描指定门路的所有 java 类。这里咱们就设置了一下 mapper 的门路。

设置开启事务

  • 优良的架构没有事务是能应用的。咱们配置事务也是很简略的。在 springboot 中咱们举荐应用 java 代码来配置事务的。上面的配置咱们为了容易浏览。配置在 TransactionConfig 类中

@Bean
public DataSourceTransactionManager primaryTransactionManager() {return new DataSourceTransactionManager(dataSource);
}
  • 首先是配置事务管理器。事务管理的是数据源。所以这里咱们须要将 MybatisConfig 中的 DataSource 加载进来。这里不多说
  • 而后配置咱们的告诉点

@Bean
public TransactionInterceptor txAdvice() {DefaultTransactionAttribute txAttr_REQUIRED = new DefaultTransactionAttribute();
    txAttr_REQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    DefaultTransactionAttribute txAttr_REQUIRED_READONLY = new DefaultTransactionAttribute();
    txAttr_REQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    txAttr_REQUIRED_READONLY.setReadOnly(true);

    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    source.addTransactionalMethod("add*", txAttr_REQUIRED);
    source.addTransactionalMethod("save*", txAttr_REQUIRED);
    source.addTransactionalMethod("delete*", txAttr_REQUIRED);
    source.addTransactionalMethod("update*", txAttr_REQUIRED);
    source.addTransactionalMethod("exec*", txAttr_REQUIRED);
    source.addTransactionalMethod("set*", txAttr_REQUIRED);
    source.addTransactionalMethod("get*", txAttr_REQUIRED_READONLY);
    source.addTransactionalMethod("query*", txAttr_REQUIRED_READONLY);
    source.addTransactionalMethod("find*", txAttr_REQUIRED_READONLY);
    source.addTransactionalMethod("list*", txAttr_REQUIRED_READONLY);
    source.addTransactionalMethod("count*", txAttr_REQUIRED_READONLY);
    source.addTransactionalMethod("is*", txAttr_REQUIRED_READONLY);
    return new TransactionInterceptor(primaryTransactionManager(), source);
}
  • 最初咱们配置一下咱们的切面、切点

@Bean
public Advisor txAdviceAdvisor() {AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
    return new DefaultPointcutAdvisor(pointcut, txAdvice());
}@Bean
public Advisor txAdviceAdvisor() {AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
    return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
  • 最初阐明下。TransactionConfig 这个类因为配置事务、拦挡所以咱们须要退出如下注解在雷伤

@Configuration
@Aspect
@EnableTransactionManagement

资源放行

  • 以上就是 mybatis 根本的一个配置了。然而这个时候还是不能应用的。因为咱们的 mapper 对应的 xml 是放在 java 目录下的。失常 src 下都是 java。xml 文件在 maven 编译时不放行的。咱们须要非凡解决下
  • 在 pom 的 build 下退出放行配置

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
            <include>**/*.properties</include>
            <include>**/*.yaml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.*</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>
  • 退出如下配置后别忘记了 clean 一下在运行。避免缓存。clean 之后看看 target 下文件

测试

  • 为了不便测试咱们须要编写测试类。

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestDataSource {
  
    @Autowired
    private TestMapper testMapper;
    
    @Test
    public void test() {List<Map<String, Object>> test = testMapper.test();
        System.out.println(test);
    }
}

后果

  • 这里是我查询数据库中的一条数据。次要是测试 springboot 整合 mybatis 的流程。到这里 mybatis 就整合完了。

思考 && 疑难

  • 下面的配置咱们是接入 mybatis 了。然而在笔者其余架构上测试过。在 MybatisConfig 这个类中配置数据源的时候能够间接 new 出 DruidDataSource 就能够了。springboot 会主动通过 DataSourceProperties 这个类获取到数据源信息的。然而笔者这里始终没有尝试胜利。至于原理更是没有搞懂了。这里留下一个彩蛋心愿晓得的敌人能说说这事怎么回事

@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {return new DruidDataSource();
}
  • 上述代码和本案例中相比就少了很多配置。尽管有的敌人说能够通过映射实体来做。然而间接 new 对象对咱们而言更简略。疑难

应用通用 mapper 性能

【详见 feature/0002/spring-mybatis-tk-page 分支】


<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.3.9</version>
</dependency>
  • 这些插件其实就是改写咱们之前学习的 myabtis 四大组件中的某一个组件而实现的。所以不论是通用 mapper 还是前面要说的 myabtis-plus 都是须要从新改写咱们的 myabtis 配置类的。
  • 首先咱们想接入通用 mapper 时,咱们须要改用 tk 提供的扫包配置

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {tk.mybatis.spring.mapper.MapperScannerConfigurer mapperScannerConfigurer = new tk.mybatis.spring.mapper.MapperScannerConfigurer();
    //MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setSqlSessionFactory(primarySqlSessionFactory());
    // 每张表对应的 *.java,interface 类型的 Java 文件
    mapperScannerConfigurer.setBasePackage("com.github.zxhtom.**.mapper");
    return mapperScannerConfigurer;
}
  • 而后增加通用 mapper 配置

@Bean()
public MapperHelper primaryMapperHelper() throws Exception {MapperHelper mapperHelper = new MapperHelper();

    Config config = mapperHelper.getConfig();
    // 表名字段名应用驼峰转下划线大写模式
    config.setStyle(Style.camelhumpAndUppercase);

    mapperHelper.registerMapper(Mapper.class);
    mapperHelper.processConfiguration(primarySqlSessionFactory().getConfiguration());
    return mapperHelper;
}
  • 测试代码就很简略了。

User user = tkMapper.selectByPrimaryKey(1);

应用 mybatis-plus

【详见 feature/0002/spring-mybatisplus 分支】

  • mybatis-plus 实际上就是通用 mapper。这里能够了解就是不同的实现。接入 mybatis-plus 其实很简略。首先咱们引入坐标


<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
  • 而后咱们创立实体

@Data
@TableName(value = "person_info_large")
public class User {@TableId(value = "id",type = IdType.AUTO)
    private Integer id;
    private String account;
    private String name;
    private String area;
    private String title;
    private String motto;
}
  • 而后就是编写咱们的 Mapper。须要继承 BaseMapper

public interface PlusMapper extends BaseMapper<User> {
}
  • 上述的编写之后根本就能够查问了。然而留神一下咱们须要批改下面的 myabtisCOnfog 这个类。因为接入 mybatisplus 后须要咱们用 mybatisplus 中的 sqlsessionbean。

@Bean
public SqlSessionFactory primarySqlSessionFactory() {
    SqlSessionFactory factory = null;
    try {MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(primaryDataSource());
        sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/github/zxhtom.**./*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.github.zxhtom.**.model");
        factory = sqlSessionFactoryBean.getObject();} catch (Exception e) {e.printStackTrace();
    }
    return factory;
}
  • 和通用 mapper 一样。就这样咱们就能够调用 BaseMapper 为咱们提供的办法操作数据库了。

@Test
public void plusTest() {User user = plusMapper.selectById(1);
    System.out.println(user);
}

应用分页插件

mybatis-plus 自带分页

【详见 feature/0002/spring-mybatisplus 分支】

  • 首先咱们应用 mybatis plus 自带的分页插件,将插件类注入到容器中

@Bean
public PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();
}
  • 而后咱们查问的结构一个 Page 对象就行了。参数别离是第几页、展现条数

return plusMapper.selectPage(page, null);
  • 就是这么简略。应用简略原理才是咱们学习的重点。喜爱 myabtis 插件原理的能够留言。抽空能够钻研

github 分页插件

【详见 feature/0002/spring-mybatis-tk-page 分支】

  • 因为 myatis-plus 自带了分页插件。下面也展现了如何应用 myabtis-plus 插件。还有一个 github 上开元的分页插件。这里就和通用 mapper 进行组合应用
  • pagehelper 官网更新还是挺怠惰的。提供了 pagehelper 和 springboot auto 拆卸两种。笔者这里测试了 pagehelper-spring-boot-starter 这个包不适宜本案例中。因为本案例中扫描 mapper 门路是通过 MapperScannerConfigurer 注册的。如果应用 pagehelper-spring-boot-starter 的话就会导致分页拦截器生效。咱们看看源码

  • 这是因为这版本提供了 springboot 主动拆卸。然而主动拆卸的代码中进行增加拦截器的时候 sqlsessionfactory 这个时候还没有进行扫描 mapper. 也就没有进行 addMapper。所以这个时候增加的拦截器拦挡不到咱们的 mapper . 如果非要应用这个版本的话。咱们扫描 mapper 就不能通过MapperScannerConfigurer . 通过笔者测试。须要在 MybatisConfig 类上增加扫描注解@MapperScan(basePackages = {"com.github.zxhtom.**.mapper"}, sqlSessionFactoryRef = "primarySqlSessionFactory")

应用惯例版本

  • 为了合乎本版本主旨。咱们这里应用如下坐标

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.7</version>
</dependency>
  • 应用这个版本 pagehelper。没有了 springboot 的主动拆卸了。咱们能够本人增加插件。增加插件有两种形式。想主动拆卸版本一样通过 Configuration 进行增加不过咱们通过 Condition 条件抉择增加的机会。
  • 还有一个简略的形式就是通过 SqlSessionFactoryBean 设置sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PageInterceptor()});
  • 因为通过 sqlsessionFactoryBean 增加的插件和在 settings 文件中增加是一样的。在通过 XmlFactory.build Configuration 对象是会主动将插件装在上。这个时候 mapper 也都扫描过了。

@Bean
public SqlSessionFactory primarySqlSessionFactory() {
    SqlSessionFactory factory = null;
    try {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(primaryDataSource());
        sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/github/zxhtom.**./*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.github.zxhtom.**.model");
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PageInterceptor()});
        factory = sqlSessionFactoryBean.getObject();} catch (Exception e) {e.printStackTrace();
    }
    return factory;
}

总结

  • 这里简略论述下为什么不实用注解扫描 mapper、或者不在配置文件中配置扫包门路。因为通过 MapperScannerConfigurer 咱们能够动态控制门路。这样显得比拟有逼格。在理论开发中笔者举荐应用注解形式扫描。因为这样能够防止不必要的坑。
  • 到这里咱们整顿了【springboot 整合 mybaits】、【mybatis-plus】、【通用 mapper】、【pagehelper 插件整合】这四个模块的整顿中咱们发现离不开 myabtis 的四大组件。springboot 其实咱们还未接触到深的内容。这篇文章次要偏差 myabtis . 后续还会持续衍生摸索【myabtis+druid】监控数据信息。
  • 喜爱钻研源码和开元框架小试牛刀的欢送关注我

代码仓库:https://gitee.com/zxhTom/spri…

退出战队

<span id=”addMe”> 退出战队 </span>

微信公众号

主题

非 xml 配置 springboot+mybatis 事务管理

退出移动版