最近自己用springboot和mybatis做了整合,记录一下:

1.先导入用到的jar包

  1.      <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5.  
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. </dependency>
  11.  
  12. <dependency>
  13. <groupId>mysql</groupId>
  14. <artifactId>mysql-connector-java</artifactId>
  15. </dependency>
  16.  
  17. <dependency>
  18. <groupId>org.mybatis.generator</groupId>
  19. <artifactId>mybatis-generator-core</artifactId>
  20. <version>1.3.3</version>
  21. </dependency>
  22.  
  23. <!-- 阿里数据源 -->
  24. <dependency>
  25. <groupId>com.alibaba</groupId>
  26. <artifactId>druid</artifactId>
  27. <version>${druid.version}</version>
  28. </dependency>
  29.  
  30. <dependency>
  31. <groupId>org.mybatis</groupId>
  32. <artifactId>mybatis-spring</artifactId>
  33. <version>1.3.0</version>
  34. </dependency>
  35.  
  36. <dependency>
  37. <groupId>org.mybatis</groupId>
  38. <artifactId>mybatis</artifactId>
  39. <version>3.4.0</version>
  40. </dependency>
  41.  
  42. <dependency>
  43. <groupId>org.springframework</groupId>
  44. <artifactId>spring-tx</artifactId>
  45. </dependency>
  46.  
  47. <dependency>
  48. <groupId>org.springframework</groupId>
  49. <artifactId>spring-jdbc</artifactId>
  50. </dependency>

2.配置配置文件(有些大家用不着的可以不配置)

  1. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  2. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://localhost:3306/test
  4. spring.datasource.username=root
  5. spring.datasource.password=
  6.  
  7. spring.datasource.initialSize=20
  8. spring.datasource.minIdle=50
  9. spring.datasource.maxActive=200
  10.  
  11. spring.datasource.maxWait=60000
  12.  
  13. spring.datasource.timeBetweenEvictionRunsMillis=60000
  14.  
  15. spring.datasource.minEvictableIdleTimeMillis=300000
  16. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  17. spring.datasource.testWhileIdle=true
  18. spring.datasource.testOnBorrow=false
  19. spring.datasource.testOnReturn=false
  20.  
  21. spring.datasource.poolPreparedStatements=true
  22. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  23.  
  24. spring.datasource.filters=stat,log4j
  25.  
  26. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  27.  
  28. #mybatis
    mybatis.mapper-locations=classpath:/com/sxf/**/*Mapper.xml
    mybatis.type-aliases-package=com.sxf.**.entity

3.解析数据源

  1. package com.sxf.config;
  2.  
  3. import java.util.Properties;
  4.  
  5. import javax.sql.DataSource;
  6.  
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  9. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import org.springframework.core.env.Environment;
  13.  
  14. import com.alibaba.druid.pool.DruidDataSource;
  15. import com.alibaba.druid.support.http.StatViewServlet;
  16. import com.alibaba.druid.support.http.WebStatFilter;
  17.  
  18. @Configuration
  19. public class DatasourceConfig {
  20.  
  21. @Autowired
  22. private Environment env;
  23.  
  24. @Bean
  25. public DataSource dataSource() {
  26. DruidDataSource druidDataSource = new DruidDataSource();
  27. druidDataSource.setDbType(env.getProperty("spring.datasource.type"));
  28. druidDataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
  29. druidDataSource.setUrl(env.getProperty("spring.datasource.url"));
  30. druidDataSource.setUsername(env.getProperty("spring.datasource.username"));
  31. druidDataSource.setPassword(env.getProperty("spring.datasource.password"));
  32.  
  33. druidDataSource.setInitialSize(Integer.parseInt(env.getProperty("spring.datasource.initialSize")));
  34. druidDataSource.setMinIdle(Integer.parseInt(env.getProperty("spring.datasource.minIdle")));
  35. druidDataSource.setMaxActive(Integer.parseInt(env.getProperty("spring.datasource.maxActive")));
  36. druidDataSource.setMaxWait(Long.parseLong(env.getProperty("spring.datasource.maxWait")));
  37. // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  38. druidDataSource.setTimeBetweenEvictionRunsMillis(
  39. Long.parseLong(env.getProperty("spring.datasource.timeBetweenEvictionRunsMillis")));
  40. // 配置一个连接在池中最小生存的时间,单位是毫秒
  41. druidDataSource.setMinEvictableIdleTimeMillis(
  42. Long.parseLong(env.getProperty("spring.datasource.minEvictableIdleTimeMillis")));
  43. druidDataSource.setValidationQuery(env.getProperty("spring.datasource.validationQuery"));
  44. druidDataSource.setTestWhileIdle(Boolean.getBoolean(env.getProperty("spring.datasource.testWhileIdle")));
  45. druidDataSource.setTestOnBorrow(Boolean.getBoolean(env.getProperty("spring.datasource.testOnBorrow")));
  46. druidDataSource.setTestOnReturn(Boolean.getBoolean(env.getProperty("spring.datasource.testOnReturn")));
  47. // 打开PSCache,并且指定每个连接上PSCache的大小
  48. druidDataSource.setPoolPreparedStatements(
  49. Boolean.getBoolean(env.getProperty("spring.datasource.poolPreparedStatements")));
  50. druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(
  51. Integer.parseInt(env.getProperty("spring.datasource.maxPoolPreparedStatementPerConnectionSize")));
  52. // 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  53.  
  54. // 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  55. String cpStr = env.getProperty("spring.datasource.connectionProperties");
  56. if (null != cpStr) {
  57. Properties pro = new Properties();
  58. String[] kvArr = cpStr.split("\\;");
  59. if (null != kvArr && kvArr.length > 0) {
  60. for (String cp : kvArr) {
  61. String[] arr = cp.split("\\=");
  62. if (null != arr && arr.length == 2) {
  63. pro.put(arr[0], arr[1]);
  64. }
  65. }
  66. }
  67. druidDataSource.setConnectProperties(pro);
  68. }
  69.  
  70. return druidDataSource;
  71. }
  72.  
  73. @Bean
  74. public ServletRegistrationBean druidServlet() {
  75. return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
  76. }
  77.  
  78. }

这里配置@MapperScan扫描mybatis接口, 不需要在每个接口里面配置@Mapper

  1. package com.sxf.config;
  2.  
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.mybatis.spring.SqlSessionFactoryBean;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.core.env.Environment;
  10. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  11. import org.springframework.core.io.support.ResourcePatternResolver;
  12. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  13. import org.springframework.transaction.PlatformTransactionManager;
  14. import org.springframework.transaction.annotation.EnableTransactionManagement;
  15.  
  16. @Configuration
  17. @EnableTransactionManagement
  18. @MapperScan(basePackages="com.sxf.**.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
  19. public class MyBatisConfig{
  20.  
  21. @Autowired
  22. private DatasourceConfig dataSource;
  23.  
  24. @Autowired
  25. private Environment env;
  26.  
  27. @Bean(name = "sqlSessionFactory")
  28. public SqlSessionFactory sqlSessionFactoryBean() {
  29. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  30. bean.setDataSource(dataSource.dataSource());
  31. bean.setTypeAliasesPackage(env.getProperty("type-aliases-package"));
  32.  
  33. //添加XML目录
  34. ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  35. try {
  36. // bean.setConfigLocation(resolver.getResource(env.getProperty("mybatis.page-plugins-config")));
  37. bean.setMapperLocations(resolver.getResources(env.getProperty("mybatis.mapper-locations")));
  38.  
  39. return bean.getObject();
  40. } catch(IllegalArgumentException e){
  41. e.printStackTrace();
  42. throw new RuntimeException(e);
  43. }catch (Exception e) {
  44. e.printStackTrace();
  45. e.getMessage();
  46. throw new RuntimeException(e);
  47. }
  48. }
  49.  
  50. @Bean
  51. public PlatformTransactionManager annotationDrivenTransactionManager() {
  52. return new DataSourceTransactionManager(dataSource.dataSource());
  53. }
  54. }

mybatis接口,不需要添加@Mapper

  1. package com.sxf.profit.mapper;
  2.  
  3. import com.sxf.profit.entity.InviteCode;
  4.  
  5. public interface InviteCodeMapper {
  6. int deleteByPrimaryKey(Long id);
  7.  
  8. int insert(InviteCode record);
  9.  
  10. int insertSelective(InviteCode record);
  11.  
  12. InviteCode selectByPrimaryKey(Long id);
  13.  
  14. int updateByPrimaryKeySelective(InviteCode record);
  15.  
  16. int updateByPrimaryKey(InviteCode record);
  17. }

4.写个测试controller,测试成功

  1. package com.sxf.controller;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RestController;
  7.  
  8. import com.sxf.profit.entity.InviteCode;
  9. import com.sxf.profit.mapper.InviteCodeMapper;
  10.  
  11. @RestController
  12. public class InviteCodeController {
  13.  
  14. @Autowired
  15. private InviteCodeMapper inviteCodeMapper;
  16.  
  17. @GetMapping("/Hello/{id}")
  18. public InviteCode selectInviteCode(@PathVariable("id") Long id){
  19. return inviteCodeMapper.selectByPrimaryKey(id);
  20. }
  21. }

成功!!!

Springboot与Mybatis整合的更多相关文章

  1. SpringBoot与Mybatis整合方式01(源码分析)

    前言:入职新公司,SpringBoot和Mybatis都被封装了一次,光用而不知道原理实在受不了,于是开始恶补源码,由于刚开始比较浅,存属娱乐,大神勿喷. 就如网上的流传的SpringBoot与Myb ...

  2. 30分钟带你了解Springboot与Mybatis整合最佳实践

    前言:Springboot怎么使用想必也无需我多言,Mybitas作为实用性极强的ORM框架也深受广大开发人员喜爱,有关如何整合它们的文章在网络上随处可见.但是今天我会从实战的角度出发,谈谈我对二者结 ...

  3. SpringBoot+Shiro+mybatis整合实战

    SpringBoot+Shiro+mybatis整合 1. 使用Springboot版本2.0.4 与shiro的版本 引入springboot和shiro依赖 <?xml version=&q ...

  4. SpringBoot系列——MyBatis整合

    前言 MyBatis官网:http://www.mybatis.org/mybatis-3/zh/index.html 本文记录springboot与mybatis的整合实例:1.以注解方式:2.手写 ...

  5. SpringBoot与Mybatis整合实例详解

    介绍 从Spring Boot项目名称中的Boot可以看出来,SpringBoot的作用在于创建和启动新的基于Spring框架的项目,它的目的是帮助开发人员很容易的创建出独立运行的产品和产品级别的基于 ...

  6. spring-boot、mybatis整合

    一.MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 X ...

  7. springBoot和MyBatis整合中出现SpringBoot无法启动时处理方式

    在springBoot和Myatis   整合中出现springBoot无法启动   并且报以下错误 Description: Field userMapper in cn.lijun.control ...

  8. springboot+Druid+mybatis整合

    一.添加Druid.MySQL连接池.mybatis依赖 <!--整合Druid--> <dependency> <groupId>com.alibaba</ ...

  9. SpringBoot与Mybatis整合的设置

    Mybatis和Spring Boot的整合有两种方式: 第一种:使用mybatis官方提供的Spring Boot整合包实现,地址:https://github.com/mybatis/spring ...

随机推荐

  1. Java起源

    Java历史发展和特点 作为一名合格的程序员,如果不了解一些关于Java语言的起源是有一些不太合适的.下面就介绍一下我所了解的Java起源. 1.Java名字的来源 Java是印度尼西亚爪哇岛的英文名 ...

  2. Java序列化详解

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt228 以前在使用hibernate时候,domain域模型的JavaBean ...

  3. 记一次wiki数据爬取过程

    最近有个爬取各国领导人信息的奇怪需求,要求百度和维基两种版本的数据,最要命的还要保持数据的结构不变.正好印象中隐约记得维基有专门的领导人列表页,不考虑爬取下来的格式不变的话应该很好爬的样子. 首先思路 ...

  4. poj 3621 二分+spfa

    题意:给出一个有向图,问求一个回路,使得回路上的点权之和/边权之和最大. 这题主要是分析出如何确定ans值.我们将(a1*x1+a2*x2+..+an*xn)/(b1*x1+b2*x2+..+bn*x ...

  5. Push or Pull?

    采用Pull模型还是Push模型是很多中间件都会面临的一个问题.消息中间件.配置管理中心等都会需要考虑Client和Server之间的交互采用哪种模型: 服务端主动推送数据给客户端? 客户端主动从服务 ...

  6. 小程序脚本语言WXS详解

    WXS脚本语言是 Weixin Script脚本的简称,是JS.JSON.WXML.WXSS之后又一大小程序内部文件类型.截至到目前小程序已经提供了5种文件类型. 解构小程序的几种方式,其中一种方式就 ...

  7. linux命令每日一练:find与rm实现查找并删除目录或文件

    linux命令每日一练 linux中find与rm实现查找并删除目录或文件 linux 下用find命令查找文件,rm命令删除文件. 删除指定目录下指定文件 find 要查找的目录名 -name .s ...

  8. 个人作业2——英语学习APP案例分析(必应词典的使用)

    第一部分 调研, 评测 1.使用环境:window 10 词典版本: 2.使用体验: 打开词典出现下面这一界面: 词典模块:出现了每日一词,每日一句,每日阅读板块,还提供了生词本,个人觉得最喜欢的是这 ...

  9. 201521123020《Java程序设计》第8周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 2. 书面作业 本次作业题集集合 1.List中指定元素的删除(题目4-1) 1.1 实验总结 运用到了equ ...

  10. 201521123065 《Java程序设计》第5周学习总结

    1. 本周学习总结 1.1 尝试使用思维导图总结有关多态与接口的知识点. 1.2 可选:使用常规方法总结其他上课内容. 1.ArrayList只能存放对象: 2.对象包装类之间使用equals进行比较 ...