接下来就是完成增删改查的功能了,首先在config包下配置Druid数据连接池,在配置之前先把相关配置在application.preperties中完善

application.preperties

  1. # 下面为连接池的补充设置,应用到上面所有数据源中
  2. # 初始化大小,最小,最大
  3. spring.datasource.initialSize=5
  4. spring.datasource.minIdle=5
  5. spring.datasource.maxActive=30
  6. # 配置获取连接等待超时的时间
  7. spring.datasource.maxWait=60000
  8. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  9. spring.datasource.timeBetweenEvictionRunsMillis=60000
  10. # 配置一个连接在池中最小生存的时间,单位是毫秒
  11. spring.datasource.minEvictableIdleTimeMillis=300000
  12. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  13. spring.datasource.testWhileIdle=true
  14. spring.datasource.testOnBorrow=false
  15. spring.datasource.testOnReturn=false
  16. # 打开PSCache,并且指定每个连接上PSCache的大小
  17. spring.datasource.poolPreparedStatements=true
  18. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  19. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  20. spring.datasource.filters=stat,wall,log4j
  21. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  22. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  23. # 合并多个DruidDataSource的监控数据
  24. spring.datasource.useGlobalDataSourceStat=true
  25. # Druid 监控 Servlet 配置参数
  26. spring.datasource.druidRegistrationUrl: /druid/*
  27. spring.datasource.resetEnable: true
  28. spring.datasource.loginUsername: admin
  29. spring.datasource.loginPassword: 1234
  30. # Druid 监控过滤相关配置参数
  31. spring.datasource.filtersUrlPatterns: /*
  32. spring.datasource.exclusions: '*.js,*.gif,*.jpg,*.jpeg,*.png,*.css,*.ico,*.jsp,/druid/*'
  33. spring.datasource.sessionStatMaxCount: 2000
  34. spring.datasource.sessionStatEnable: true
  35. spring.datasource.principalSessionName: session_user_key
  36. spring.datasource.profileEnable: true
  37. #druid datasouce database settings end

上面配置完之后开始完成Druid数据连接池配置

在config包->新建DruidDbConfig类

DruidDBConfig类

  1. @Configuration
  2. public class DruidDBConfig {
  3. // private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
  4. @Value("${spring.datasource.driver-class-name}")
  5. private String driverClassName;
  6. @Value("${spring.datasource.url}")
  7. private String dbUrl;
  8. @Value("${spring.datasource.username}")
  9. private String username;
  10. @Value("${spring.datasource.password}")
  11. private String password;
  12. @Value("${spring.datasource.initialSize}")
  13. private int initialSize;
  14. @Value("${spring.datasource.minIdle}")
  15. private int minIdle;
  16. @Value("${spring.datasource.maxActive}")
  17. private int maxActive;
  18. @Value("${spring.datasource.maxWait}")
  19. private int maxWait;
  20. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  21. private int timeBetweenEvictionRunsMillis;
  22. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  23. private int minEvictableIdleTimeMillis;
  24. @Value("${spring.datasource.validationQuery}")
  25. private String validationQuery;
  26. @Value("${spring.datasource.testWhileIdle}")
  27. private boolean testWhileIdle;
  28. @Value("${spring.datasource.testOnBorrow}")
  29. private boolean testOnBorrow;
  30. @Value("${spring.datasource.testOnReturn}")
  31. private boolean testOnReturn;
  32. @Value("${spring.datasource.poolPreparedStatements}")
  33. private boolean poolPreparedStatements;
  34. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  35. private int maxPoolPreparedStatementPerConnectionSize;
  36. @Value("${spring.datasource.filters}")
  37. private String filters;
  38. @Value("{spring.datasource.connectionProperties}")
  39. private String connectionProperties;
  40. @Bean //声明其为Bean实例
  41. @Primary //在同样的DataSource中,首先使用被标注的DataSource
  42. public DataSource dataSource(){
  43. DruidDataSource datasource = new DruidDataSource();
  44. datasource.setUrl(this.dbUrl);
  45. datasource.setUsername(username);
  46. datasource.setPassword(password);
  47. datasource.setDriverClassName(driverClassName);
  48. //configuration
  49. datasource.setInitialSize(initialSize);
  50. datasource.setMinIdle(minIdle);
  51. datasource.setMaxActive(maxActive);
  52. datasource.setMaxWait(maxWait);
  53. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  54. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  55. datasource.setValidationQuery(validationQuery);
  56. datasource.setTestWhileIdle(testWhileIdle);
  57. datasource.setTestOnBorrow(testOnBorrow);
  58. datasource.setTestOnReturn(testOnReturn);
  59. datasource.setPoolPreparedStatements(poolPreparedStatements);
  60. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  61. try {
  62. datasource.setFilters(filters);
  63. } catch (SQLException e) {
  64. // logger.error("druid configuration initialization filter", e);
  65. }
  66. datasource.setConnectionProperties(connectionProperties);
  67. return datasource;
  68. }
  69. }

上述配置中的日志已经注释了,如果需要配置可以在resources中加入logback-spring.xml:

resources->logback-spring.xml

logback-spring.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration scan="true" scanPeriod="60 seconds" debug="false">
  3. <contextName>logback</contextName>
  4. <!--自己定义一个log.path用于说明日志的输出目录-->
  5. <property name="log.path" value="/log/jiangfeixiang/"/>
  6. <!--输出到控制台-->
  7. <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
  8. <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
  9. <level>ERROR</level>
  10. </filter>-->
  11. <encoder>
  12. <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
  13. </encoder>
  14. </appender>
  15. <!--输出到文件-->
  16. <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
  17. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  18. <fileNamePattern>${log.path}/logback.%d{yyyy-MM-dd}.log</fileNamePattern>
  19. </rollingPolicy>
  20. <encoder>
  21. <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
  22. </encoder>
  23. </appender>
  24. <root level="debug">
  25. <appender-ref ref="console"/>
  26. <appender-ref ref="file"/>
  27. </root>
  28. <!-- logback为java中的包 -->
  29. <logger name="com.example.springboootmybatis.controller"/>
  30. </configuration>

UserServiec接口

  1. public interface UserService {
  2. /**
  3. * 查询所有用户
  4. */
  5. public List<User> getAllUser();
  6. /**
  7. * 保存用户
  8. * @param user
  9. */
  10. void saveUser(User user);
  11. /**
  12. * 根据id查询用户
  13. */
  14. User getById(Integer id);
  15. /**
  16. * 校验用户名
  17. * @param userName
  18. * @return
  19. */
  20. Boolean checkUserName(String userName);
  21. /**
  22. * 修改用户
  23. * @param user
  24. */
  25. void updateUser(User user);
  26. /**
  27. * 根据id删除用户
  28. * @param id
  29. */
  30. void deleteUser(Integer id);
  31. /**
  32. * 全选删除
  33. * @param useridList
  34. */
  35. void deleteBatchUser(List<Integer> useridList);
  36. }

UserServiceImpl实现类

  1. @Service
  2. @Transactional
  3. public class UserServiceImpl implements UserService {
  4. //注入
  5. @Autowired
  6. private UserMapper userMapper;
  7. /**
  8. * 查询所有用户
  9. */
  10. @Override
  11. public List<User> getAllUser() {
  12. List<User> users = userMapper.selectByExample(null);
  13. return users;
  14. }
  15. /**
  16. * 根据id查询用户
  17. */
  18. @Override
  19. public User getById(Integer id) {
  20. User user = userMapper.selectByPrimaryKey(id);
  21. return user;
  22. }
  23. /**
  24. * 添加用户
  25. * @param user
  26. */
  27. @Override
  28. public void saveUser(User user) {
  29. userMapper.insertSelective(user);
  30. }
  31. /**
  32. * 校验用户名是否存在
  33. * @param userName
  34. * @return
  35. * 数据库没有这条记录,count==0,返回true
  36. */
  37. @Override
  38. public Boolean checkUserName(String userName) {
  39. UserExample example=new UserExample();
  40. UserExample.Criteria criteria=example.createCriteria();
  41. criteria.andUsernameEqualTo(userName);
  42. long count=userMapper.countByExample(example);
  43. if(count==0){
  44. return true;
  45. }
  46. return false;
  47. }
  48. /**
  49. * 修改用户
  50. * @param user
  51. */
  52. @Override
  53. public void updateUser(User user) {
  54. userMapper.updateByPrimaryKeySelective(user);
  55. }
  56. /**
  57. * 根据id删除(单个)
  58. * @param id
  59. */
  60. @Override
  61. public void deleteUser(Integer id) {
  62. userMapper.deleteByPrimaryKey(id);
  63. }
  64. /**
  65. * 批量删除
  66. * @param useridList
  67. */
  68. @Override
  69. public void deleteBatchUser(List<Integer> useridList) {
  70. /* UserExample example=new UserExample();
  71. UserExample.Criteria criteria=example.createCriteria();
  72. criteria.andUseridIn(useridList);
  73. userMapper.deleteByExample(example);*/
  74. }
  75. }

UserController

  1. @RestController
  2. @RequestMapping(value = "/user")
  3. public class UserController {
  4. //注入
  5. @Autowired
  6. private UserService userService;
  7. /**
  8. * 查询所有用户
  9. */
  10. @ApiOperation(value="获取用户列表")
  11. @RequestMapping(value = "/user",method = RequestMethod.GET)
  12. public List<User> getListAll(){
  13. List<User> listAll = userService.getAllUser();
  14. return listAll;
  15. }
  16. /**
  17. * 用户保存
  18. * @return
  19. */
  20. @ApiOperation(value = "添加用户",notes = "根据user添加用户")
  21. @ApiImplicitParam(name = "user",value = "用户user",required = true,dataType = "User")
  22. @RequestMapping(value = "/users",method = RequestMethod.POST)
  23. public String saveUser(@RequestBody User user){
  24. userService.saveUser(user);
  25. return "success";
  26. }
  27. /**
  28. * 根据id查询
  29. */
  30. @ApiOperation(value = "根据id查询")
  31. @ApiImplicitParam(name = "id",value = "用户id")
  32. @RequestMapping(value = "/{id}",method = RequestMethod.GET)
  33. public User getById(@PathVariable("id") Integer id){
  34. User user = userService.getById(id);
  35. return user;
  36. }
  37. /**
  38. * 校验用户名
  39. * @param username
  40. * @return
  41. */
  42. @ApiOperation(value = "校验用户名")
  43. @ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String")
  44. @RequestMapping(value = "/{username}",method = RequestMethod.POST)
  45. public Boolean checkUserName(@PathVariable("username")String username){
  46. Boolean aboolean = userService.checkUserName(username);
  47. if (aboolean){
  48. return true;
  49. }else {
  50. return false;
  51. }
  52. }
  53. /**
  54. * 修改用户
  55. * @param user
  56. */
  57. @ApiOperation(value = "修改用户")
  58. @ApiImplicitParam(name = "user",value = "用户",required = true,dataType = "User")
  59. @RequestMapping(value = "/user",method = RequestMethod.PUT)
  60. public String updateUser(@RequestBody User user){
  61. userService.updateUser(user);
  62. return "success";
  63. }
  64. /**
  65. * 根据id删除用户
  66. */
  67. @ApiOperation(value = "根据id删除用户")
  68. @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Integer")
  69. @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
  70. public String deleteUser(@PathVariable Integer id){
  71. userService.deleteUser(id);
  72. return "success";
  73. }
  74. }

controller类中使用了swgger2如下:

springboot中整合swgger2

pom.xml

  1. <!--swgger2-->
  2. <dependency>
  3. <groupId>io.springfox</groupId>
  4. <artifactId>springfox-swagger2</artifactId>
  5. <version>2.2.2</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>io.springfox</groupId>
  9. <artifactId>springfox-swagger-ui</artifactId>
  10. <version>2.2.2</version>
  11. </dependency>

springbootmybatis包下创建SwaggerConfig.java

SwaggerConfig

  1. @Configuration
  2. @EnableSwagger2
  3. public class SwaggerConfig {
  4. @Bean
  5. public Docket createRestApi() {
  6. ApiInfo apiInfo = new ApiInfoBuilder()
  7. .title("使用Swagger2构建RESTful APIs") //标题
  8. .description("客户端与服务端接口文档") //描述
  9. .termsOfServiceUrl("http://localost:8080") //域名地址
  10. .contact("姜飞祥") //作者
  11. .version("1.0.0") //版本号
  12. .build();
  13. return new Docket(DocumentationType.SWAGGER_2)
  14. .apiInfo(apiInfo)
  15. .select()
  16. .apis(RequestHandlerSelectors.basePackage("com.example.springbootmybatis"))
  17. .paths(PathSelectors.any())
  18. .build();
  19. }
  20. }

以上就算完成了,写的不好请见谅。具体测试请参考下面的springboot整合swgger2,之后访问http://localhost:8080/swagger-ui.html即可,和

备注:

springboot整合mybatis增删改查(四):完善增删改查及整合swgger2的更多相关文章

  1. SpringBoot结合Mybatis 使用 mapper*.xml 进行数据库增删改查操作

    什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索. MyBa ...

  2. SpringBoot之整合Mybatis(增,改,删)

    一,在上一篇文章SpringBoot之整合Mybatis中,我们使用spring boot整合了Mybatis,并演示了查询操作.接下来我们将完善这个示例,增加增,删,改的功能. 二,改动代码 1.修 ...

  3. Spring学习总结(六)——Spring整合MyBatis完整示例

    为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简 ...

  4. spring 框架整合mybatis的源码分析

    问题:spring 在整合mybatis的时候,我们是看不见sqlSessionFactory,和sqlsession(sqlsessionTemplate 就是sqlsession的具体实现)的,这 ...

  5. SpringBoot整合Mybatis对单表的增、删、改、查操作

    一.目标 SpringBoot整合Mybatis对单表的增.删.改.查操作 二.开发工具及项目环境 IDE: IntelliJ IDEA 2019.3 SQL:Navicat for MySQL 三. ...

  6. Spring Boot入门系列(六)如何整合Mybatis实现增删改查

    前面介绍了Spring Boot 中的整合Thymeleaf前端html框架,同时也介绍了Thymeleaf 的用法.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/z ...

  7. Spring Boot入门系列(十八)整合mybatis,使用注解的方式实现增删改查

    之前介绍了Spring Boot 整合mybatis 使用xml配置的方式实现增删改查,还介绍了自定义mapper 实现复杂多表关联查询.虽然目前 mybatis 使用xml 配置的方式 已经极大减轻 ...

  8. springboot集成mybatis环境搭建以及实现快速开发微服务商品模块基本的增删改查!

    之前学习了springboot和mybatis3的一些新特性,初步体会了springboot的强大(真的好快,,,,,),最近趁着复习,参考着以前学习的教程,动手写了一个springboot实战的小例 ...

  9. spring boot整合mybatis框架及增删改查(jsp视图)

    工具:idea.SQLyog 版本:springboot1.5.9版本.mysql5.1.62 第一步:新建项目 第二步:整合依赖(pom.xml) <dependencies> < ...

  10. springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)

    这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...

随机推荐

  1. 小型网站MYSQL问题二:Percona Xtrabackup实现数据库备份和恢复

    1.安装软件仓库(不要问我为什么不用源码安装,好吧,其实我懒.) 1 2 3 4 5 6 7 8 wget https://www.percona.com/downloads/percona-rele ...

  2. Linux系统——http协议原理

    Web服务基础 用户访问网页基本流程 (1)在浏览器中输入域名,系统会查找系统本地的DNS缓存及hosts文件信息,查找是否存在域名对应的IP解析记录 (2)DNS解析域名为IP地址,系统会把浏览器的 ...

  3. 手把手教你学node.js之学习使用外部模块

    学习使用外部模块 目标 建立一个 lesson2 项目,在其中编写代码. 当在浏览器中访问 http://localhost:3000/?q=alsotang 时,输出 alsotang 的 md5 ...

  4. python中的切片

    python中提供了一种很方便的方法来完成取出指定范围内的元素,这种方法就是切片(Slice). 以下为切片的例子: In [1]: L = ['Michael', 'Sarah', 'Tracy', ...

  5. Java transient关键字的理解

    transient [ˈtrænziənt] adj. 短暂的; 转瞬即逝的; 临时的 n 临时旅客; 瞬变现象; 候鸟; 1. transient的作用及使用方法       我们都知道一个对象只要 ...

  6. 浅谈padding

    浅谈padding padding是CSS盒子模型的一部分,代表盒子模型的内边距. 用法 padding属性有四个值,分别代表上.右.下.左的内边距. .box { padding: 10px 5px ...

  7. 日志自定义Tag

    import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; /** * Crea ...

  8. Shell脚本之无限循环的两种方法

    for #!/bin/bash ;i<;)) do let "j=j+1" echo "-------------j is $j ----------------- ...

  9. 解决"No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android"错误

    今天安装了Android Studio 3.2,打开一个旧工程,编译提示"No toolchains found in the NDK toolchains folder for ABI w ...

  10. Mysql语句转义

    String sqlStr = "SELECT * FROM t_sys_dic WHERE idPath LIKE" + "'" + "/19/20 ...