接下來就是完成增刪改查的功能了,首先在config包下配置Druid數據鏈接池,在配置以前先把相關配置在application.preperties中完善css
# 下面爲鏈接池的補充設置,應用到上面全部數據源中 # 初始化大小,最小,最大 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數據鏈接池配置html
在config包->新建DruidDbConfig類java
@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:spring
resources->logback-spring.xmlsql
<?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>
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);*/ } }
@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以下:api
pom.xmlspringboot
<!--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.javasession
@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便可,和mybatis