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

application.preperties

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

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

在config包->新建DruidDbConfig类

DruidDBConfig类

@Configuration
public class DruidDBConfig {
// private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class); @Value("${spring.datasource.driver-class-name}")
private String driverClassName; @Value("${spring.datasource.url}")
private String dbUrl; @Value("${spring.datasource.username}")
private String username; @Value("${spring.datasource.password}")
private String password; @Value("${spring.datasource.initialSize}")
private int initialSize; @Value("${spring.datasource.minIdle}")
private int minIdle; @Value("${spring.datasource.maxActive}")
private int maxActive; @Value("${spring.datasource.maxWait}")
private int maxWait; @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis; @Value("${spring.datasource.validationQuery}")
private String validationQuery; @Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle; @Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow; @Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn; @Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements; @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.filters}")
private String filters; @Value("{spring.datasource.connectionProperties}")
private String connectionProperties; @Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName); //configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
// logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties); return datasource;
}
}

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

resources->logback-spring.xml

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>logback</contextName>
<!--自己定义一个log.path用于说明日志的输出目录-->
<property name="log.path" value="/log/jiangfeixiang/"/>
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>-->
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender> <!--输出到文件-->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/logback.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender> <root level="debug">
<appender-ref ref="console"/>
<appender-ref ref="file"/>
</root> <!-- logback为java中的包 -->
<logger name="com.example.springboootmybatis.controller"/>
</configuration>

UserServiec接口

public interface UserService {
/**
* 查询所有用户
*/
public List<User> getAllUser(); /**
* 保存用户
* @param user
*/
void saveUser(User user); /**
* 根据id查询用户
*/
User getById(Integer id); /**
* 校验用户名
* @param userName
* @return
*/
Boolean checkUserName(String userName); /**
* 修改用户
* @param user
*/
void updateUser(User user); /**
* 根据id删除用户
* @param id
*/
void deleteUser(Integer id); /**
* 全选删除
* @param useridList
*/
void deleteBatchUser(List<Integer> useridList);
}

UserServiceImpl实现类

@Service
@Transactional
public class UserServiceImpl implements UserService {
//注入
@Autowired
private UserMapper userMapper; /**
* 查询所有用户
*/
@Override
public List<User> getAllUser() {
List<User> users = userMapper.selectByExample(null);
return users;
} /**
* 根据id查询用户
*/
@Override
public User getById(Integer id) {
User user = userMapper.selectByPrimaryKey(id);
return user;
} /**
* 添加用户
* @param user
*/
@Override
public void saveUser(User user) {
userMapper.insertSelective(user);
} /**
* 校验用户名是否存在
* @param userName
* @return
* 数据库没有这条记录,count==0,返回true
*/
@Override
public Boolean checkUserName(String userName) {
UserExample example=new UserExample();
UserExample.Criteria criteria=example.createCriteria();
criteria.andUsernameEqualTo(userName);
long count=userMapper.countByExample(example);
if(count==0){
return true;
}
return false;
} /**
* 修改用户
* @param user
*/
@Override
public void updateUser(User user) {
userMapper.updateByPrimaryKeySelective(user);
} /**
* 根据id删除(单个)
* @param id
*/
@Override
public void deleteUser(Integer id) {
userMapper.deleteByPrimaryKey(id);
} /**
* 批量删除
* @param useridList
*/
@Override
public void deleteBatchUser(List<Integer> useridList) {
/* UserExample example=new UserExample();
UserExample.Criteria criteria=example.createCriteria();
criteria.andUseridIn(useridList);
userMapper.deleteByExample(example);*/ }
}

UserController

@RestController
@RequestMapping(value = "/user")
public class UserController {
//注入
@Autowired
private UserService userService; /**
* 查询所有用户
*/
@ApiOperation(value="获取用户列表")
@RequestMapping(value = "/user",method = RequestMethod.GET)
public List<User> getListAll(){
List<User> listAll = userService.getAllUser();
return listAll;
} /**
* 用户保存
* @return
*/
@ApiOperation(value = "添加用户",notes = "根据user添加用户")
@ApiImplicitParam(name = "user",value = "用户user",required = true,dataType = "User")
@RequestMapping(value = "/users",method = RequestMethod.POST)
public String saveUser(@RequestBody User user){
userService.saveUser(user);
return "success";
} /**
* 根据id查询
*/
@ApiOperation(value = "根据id查询")
@ApiImplicitParam(name = "id",value = "用户id")
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public User getById(@PathVariable("id") Integer id){
User user = userService.getById(id);
return user;
} /**
* 校验用户名
* @param username
* @return
*/
@ApiOperation(value = "校验用户名")
@ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String")
@RequestMapping(value = "/{username}",method = RequestMethod.POST)
public Boolean checkUserName(@PathVariable("username")String username){
Boolean aboolean = userService.checkUserName(username);
if (aboolean){
return true;
}else {
return false;
}
} /**
* 修改用户
* @param user
*/
@ApiOperation(value = "修改用户")
@ApiImplicitParam(name = "user",value = "用户",required = true,dataType = "User")
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String updateUser(@RequestBody User user){
userService.updateUser(user);
return "success";
} /**
* 根据id删除用户
*/
@ApiOperation(value = "根据id删除用户")
@ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Integer")
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Integer id){
userService.deleteUser(id);
return "success";
}
}

controller类中使用了swgger2如下:

springboot中整合swgger2

pom.xml

<!--swgger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>

springbootmybatis包下创建SwaggerConfig.java

SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("使用Swagger2构建RESTful APIs") //标题
.description("客户端与服务端接口文档") //描述
.termsOfServiceUrl("http://localost:8080") //域名地址
.contact("姜飞祥") //作者
.version("1.0.0") //版本号
.build(); return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.springbootmybatis"))
.paths(PathSelectors.any())
.build();
} }

以上就算完成了,写的不好请见谅。具体测试请参考下面的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. JDBC连接数据库(一)

    原文地址http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html JDBC连接数据库 创建一个以JDBC连接数据库的程序,包含7个步 ...

  2. cocos代码研究(25)Widget子类PageView学习笔记

    基础理论 ListView控件是一个显示滚动项目列表的视图组. 列表项是通过使用addChild或insertDefaultItem插入到列表中的,继承自ScrollView. 代码实践 static ...

  3. HDU 1879 继续畅通工程(Prim||Kruscal模板题)

    原题链接 Prim(点归并) //异或运算:相同为假,不同为真 #include<cstdio> #include<algorithm> #define maxn 105 us ...

  4. ng-深度学习-课程笔记-4: 浅层神经网络(Week3)

    1 神经网络概览( Neural Networks Overview ) 先来快速过一遍如何实现神经网络. 首先需要输入特征x,参数w和b,计算出z,然后用激活函数计算出a,在神经网络中我们要做多次这 ...

  5. bzoj1611 / P2895 [USACO08FEB]流星雨Meteor Shower

    P2895 [USACO08FEB]流星雨Meteor Shower 给每个点标记一下能够走的最迟时间,蓝后bfs处理一下 #include<iostream> #include<c ...

  6. 这才是官方的tapable中文文档

    起因 搜索引擎搜索tapable中文文档,你会看见各种翻译,点进去一看,确实是官方的文档翻译过来的,但是webpack的文档确实还有很多需要改进的地方,既然是开源的为什么不去github上的tapab ...

  7. 高级Bash脚本编程(一)

    高级Bash脚本编程 Bash 它是能力很强的计算机语言,被称为解释性语言或脚本语言,它可以调用所有的UNIX命令和工具再加上公共程序. Bash中的特殊字符 注释(#) (除#!外,#!是用于指定当 ...

  8. NO.1 在Eclipse中安装Maven插件安装详解

    前言 本来是没打算写博客的,作为一个13年毕业的菜鸟,自认为水平太渣写不出什么好文章,但是前些日子看到一篇鼓励性质的文章说,技术人员的成长靠的就是点点滴滴的积累,博客内容不一定包含多么高深的内容,但是 ...

  9. Codeforces Round #394 (Div. 2) C.Dasha and Password(暴力)

    http://codeforces.com/contest/761/problem/C 题意:给出n个串,每个串的初始光标都位于0(列)处,怎样移动光标能够在凑出密码(每个串的光标位置表示一个密码的字 ...

  10. Mac adb 安装

    一.下载Android studio https://developer.android.google.cn/studio/ 二.安装 首先移动 弹出下面弹框,直接点击OK 提示无法访问Android ...