spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件

开篇:

使用自动生成工具,生成的代码,xml文件等,将非常好的支持增删改,分页查询,条件查询等

一.创建spring boot

1.1idea创建,点击new project,然后一路next下去

 spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件_第1张图片

1.2,设置maven自动导入,setting文件添加阿里云镜像

 

        nexus-aliyun

        *

        Nexus aliyun

        http://maven.aliyun.com/nexus/content/groups/public

    

 

1.3,添加pom依赖,让工程跑起来


   org.springframework.boot
   spring-boot-starter-web

在添加build


   
      
         org.springframework.boot
         spring-boot-maven-plugin
      
      
         org.mybatis.generator
         mybatis-generator-maven-plugin
         1.3.2
         
            
            src/main/resources/generatorConfig.xml
            true
            true
         
         
            
               Generate MyBatis Artifacts
               
                  generate
               
            
         
         
            
               org.mybatis.generator
               mybatis-generator-core
               1.3.2
            
         
      
   
   
      
         src/main/java
         
            **/*.xml
         
         true
      
   

同时添加mybatis整合springboot依赖,跟mysql依赖


   org.mybatis.spring.boot
   mybatis-spring-boot-starter
   1.1.1



   mysql
   mysql-connector-java
   5.1.35

 

1.3,将自动生成代码文件放入resource资源文件下,文件名为generatorConfig.xml

xml version="1.0"encoding="UTF-8"?>
generatorConfiguration
        PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


    
    location="D:\maven\repository\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar"/>
    id="testTables"targetRuntime="MyBatis3">
        
            
            name="suppressAllComments"value="true"/>
        
        
        driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"userId="root"
                        password="123">
        
        
        
            name="forceBigDecimals"value="false"/>
        

        
        targetPackage="com.example.mapper.pojo"
                            targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
            
            name="trimStrings"value="true"/>
        
        
        targetPackage="com.example.mapper"
                         targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
        
        
        type="XMLMAPPER"
                             targetPackage="com.example.mapper"
                             targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
        
        
        schema=""tableName="userinfo">
        
    

 

二.创建数据库

2.1 建表语句如下:

CREATE TABLE `user` (

  `id` int(20) NOT NULL AUTO_INCREMENT,

  `username` varchar(20) DEFAULT NULL,

  `password` varchar(20) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

2.2,修改generatorConfig.xml文件,修改文件后如下

?xml version="1.0"encoding="UTF-8"?>
generatorConfiguration
        PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


    
    location="D:\maven\repository\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar"/>
    id="testTables"targetRuntime="MyBatis3">
        
            
            name="suppressAllComments"value="true"/>
        
        
        driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"userId="root"
                        password="123">
        
        
        
            name="forceBigDecimals"value="false"/>
        

        
        targetPackage="com.example.demo.mapper.pojo"
                            targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
            
            name="trimStrings"value="true"/>
        
        
        targetPackage="com.example.mapper"
                         targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
        
        
        type="XMLMAPPER"
                             targetPackage="com.example.mapper"
                             targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
        
        
        schema=""tableName="user">
        
    

2.3,添加application.properties的数据源

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

2.4.点击maven里的生成按钮,生成mapper等文件

 spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件_第2张图片

2.5.生成后的目录如下,并且工程启动没有错误

 spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件_第3张图片

2.6 DemoApplication启动类上添加注解

@MapperScan(basePackages= {"com.demo.mapper"})
@ComponentScan(basePackages= {"com.demo"})

 

三.实现增删改以及分页查询

3.1 service层的接口以及实现类

public interfaceUserService {
    List getAll();
}

@Service
public class UserServiceImplimplementsUserService {

    @Autowired
    UserMapperuserMapper;

    @Override
    publicListgetAll() {
        UserExample userExample = new UserExample();
        userExample.setDistinct(true);
        return userMapper.selectByExample(userExample);
    }
}

3.2 controller如下,启动浏览器或者postman可测试返回数据

 

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserServiceuserServiceImpl;

    /**
     * 查询
     *
@return
     
*/
    
@RequestMapping(value="/demo",method= RequestMethod.GET)
    @ResponseBody
    publicObjectgetUsers(){
        returnuserServiceImpl.getAll();
    }


}

 

3.3 利用RowBounds进行分页查询

一,usermapperusermapper.xml添加如下代码

ListselectByExampleWithBounds(UserExample example,RowBounds rowBounds);

二,userserviceuserserviceimpl分别添加如下代码

ListgetPage(intpageSize,intpageNo);

@Override
public ListgetPage(intpageSize,intpageNo) {
    RowBounds rowBounds = newRowBounds(pageNo,pageSize);
    UserExample userExample =newUserExample();
    userExample.setDistinct(true);
     return userMapper.selectByExampleWithBounds(userExample,rowBounds);
}

二.Usercontroller添加如下代码

/**
 * 利用mybatis的rowbounds分页类,分页查询
 */
@RequestMapping(value="/page",method= RequestMethod.GET)
@ResponseBody
public ObjectgetPage(@RequestParam(name="pageSize") String pageSize,
                        @RequestParam(name="pageNo") String pageNo){
    try{
        String size = pageSize;
        int pageSizes=5,nos=1;
        if(StringUtils.isNotBlank(size)){
            pageSizes = Integer.parseInt(pageSize);
        }
        String no = pageNo;
        if(StringUtils.isNotBlank(no)){
            nos = Integer.parseInt(no);
        }
        returnuserServiceImpl.getPage(pageSizes,nos);
    }catch(Exception ex){
        ex.getMessage();
    }
    return null;
}

三.请求路径上添加pagesizepageno这连个参数,可正常返回分页

四.整合日志

4.1 pom.xml添加依赖如下


   org.springframework.boot
   spring-boot-starter-logging

 

4.2 resource资源目录下添加logback.xml文件如下

xml version="1.0"encoding="UTF-8"?>
debug="false">
   
   name="LOG_HOME"value="/workspace/example"/>
   
   name="STDOUT"class="ch.qos.logback.core.ConsoleAppender">
      class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
         
         %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
      

   
   
   name="DAYINFO"  class="ch.qos.logback.core.rolling.RollingFileAppender">
      class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
         
         ${LOG_HOME}/TestSpringBoot_info.log.%d{yyyy-MM-dd}.log
         
         30
      

      
      class="ch.qos.logback.classic.filter.LevelFilter">
         info
         ACCEPT
         DENY
      
      class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
         
         %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
      

      
      class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
         10MB
      
   

   
   name="DAYERROR"  class="ch.qos.logback.core.rolling.RollingFileAppender">
      class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
         
         ${LOG_HOME}/TestSpringBoot_error.log.%d{yyyy-MM-dd}.log
         
         30
      

      
      class="ch.qos.logback.classic.filter.LevelFilter">
         error
         ACCEPT
         DENY
      
      class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
         
         %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
      

      
      class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
         10MB
      
   

   
   level="INFO">
      ref="STDOUT"/>
      ref="DAYINFO"/>
      ref="DAYERROR"/>
   

4.3.启动项目,访问分页查询接口,可看到如下日子生成文件

 spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件_第4张图片

五.整合定时任务

5.1 DemoApplication添加注解

@EnableScheduling

5.2 添加定时启动类

@Component
public class Task {

    Logger logger= LoggerFactory.getLogger(Task.class);

    @Autowired
    UserServiceuserServiceImpl;

    @Scheduled(cron="0/5 * * * * ?")
    public voidtest(){
        //加入fastJson依赖
        /*
         com.alibaba
         fastjson
         1.2.46
      */
        List users =userServiceImpl.getAll();
        String str = JSONObject.toJSONString(users);
        logger.info(str);
    }
}

 

 

六.整合druid连接池

6.1pom.xml文件添加依赖


   com.alibaba
   druid-spring-boot-starter
   1.1.6

 

6.2,application.properties的配置文件如下:

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM t_user
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=true
spring.datasource.druid.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.druid.useGlobalDataSourceStat=true
#mybatis.mapperLocations=classpath:mybatis/*.xml

七.所有源码如下

 spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件_第5张图片

 

Task

package com.demo.job;

import com.alibaba.fastjson.JSONObject;
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class Task {

    Logger logger= LoggerFactory.getLogger(Task.class);

    @Autowired
    UserServiceuserServiceImpl;

    @Scheduled(cron="0 30 * * * ?")
    public voidtest(){
        //加入fastJson依赖
        /*
         com.alibaba
         fastjson
         1.2.46
      */
        List users =userServiceImpl.getAll();
        String str = JSONObject.toJSONString(users);
        logger.info(str);
    }
}

UserMapper

package com.demo.mapper;

import com.demo.pojo.User;
import com.demo.pojo.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {
    intcountByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    ListselectByExample(UserExample example);

    ListselectByExampleWithBounds(UserExample example,RowBounds rowBounds);

    UserselectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

UserMapper.xml

xml version="1.0"encoding="UTF-8"?>
mapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
namespace="com.demo.mapper.UserMapper">
  id="BaseResultMap"type="com.demo.pojo.User">
    column="id"property="id"jdbcType="INTEGER"/>
    column="username"property="username"jdbcType="VARCHAR"/>
    column="password"property="password"jdbcType="VARCHAR"/>
  

  id="Example_Where_Clause">
    
      collection="oredCriteria"item="criteria"separator="or">
        test="criteria.valid">
          prefix="("suffix=")"prefixOverrides="and">
            collection="criteria.criteria"item="criterion">
              
                test="criterion.noValue">
                  and ${criterion.condition}
                

                test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                

                test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                

                test="criterion.listValue">
                  and ${criterion.condition}
                  collection="criterion.value"item="listItem"open="("close=")"separator=",">
                    #{listItem}
                  

                
              
            

          
        
      
    
  

  id="Update_By_Example_Where_Clause">
    
      collection="example.oredCriteria"item="criteria"separator="or">
        test="criteria.valid">
          prefix="("suffix=")"prefixOverrides="and">
            collection="criteria.criteria"item="criterion">
              
                test="criterion.noValue">
                  and ${criterion.condition}
                

                test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                

                test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                

                test="criterion.listValue">
                  and ${criterion.condition}
                  collection="criterion.value"item="listItem"open="("close=")"separator=",">
                    #{listItem}
                  

                
              
            

          
        
      
    
  

  id="Base_Column_List">
    id, username, password
  

  
  
  
  id="deleteByPrimaryKey"parameterType="java.lang.Integer">
    delete from user
    where id = #{id,jdbcType=INTEGER}
  

  id="deleteByExample"parameterType="com.demo.pojo.UserExample">
    delete from user
    test="_parameter != null">
      refid="Example_Where_Clause"/>
    
  

  id="insert"parameterType="com.demo.pojo.User">
    insert into user (id, username, password
      )
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  

  id="insertSelective"parameterType="com.demo.pojo.User">
    insert into user
    prefix="("suffix=")"suffixOverrides=",">
      test="id != null">
        id,
      

      test="username != null">
        username,
      

      test="password != null">
        password,
      

    
    prefix="values ("suffix=")"suffixOverrides=",">
      test="id != null">
        #{id,jdbcType=INTEGER},
      

      test="username != null">
        #{username,jdbcType=VARCHAR},
      

      test="password != null">
        #{password,jdbcType=VARCHAR},
      

    

  

  
  id="updateByExampleSelective"parameterType="map">
    update user
    
      test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      

      test="record.username != null">
        username = #{record.username,jdbcType=VARCHAR},
      

      test="record.password != null">
        password = #{record.password,jdbcType=VARCHAR},
      

    
    test="_parameter != null">
      refid="Update_By_Example_Where_Clause"/>
    

  

  id="updateByExample"parameterType="map">
    update user
    set id = #{record.id,jdbcType=INTEGER},
      username = #{record.username,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR}
    test="_parameter != null">
      refid="Update_By_Example_Where_Clause"/>
    
  

  id="updateByPrimaryKeySelective"parameterType="com.demo.pojo.User">
    update user
    
      test="username != null">
        username = #{username,jdbcType=VARCHAR},
      

      test="password != null">
        password = #{password,jdbcType=VARCHAR},
      

    
    where id = #{id,jdbcType=INTEGER}
  

  id="updateByPrimaryKey"parameterType="com.demo.pojo.User">
    update user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  

User

package com.demo.pojo;

public class User {
    privateIntegerid;

    private Stringusername;

    private Stringpassword;

    public IntegergetId() {
        returnid;
    }

    public voidsetId(Integer id) {
        this.id= id;
    }

    publicStringgetUsername() {
        returnusername;
    }

    public voidsetUsername(String username) {
        this.username= username ==null?null: username.trim();
    }

    publicStringgetPassword() {
        returnpassword;
    }

    public voidsetPassword(String password) {
        this.password= password ==null?null: password.trim();
    }
}

UserExample

package com.demo.pojo;

import java.util.ArrayList;
import java.util.List;

public class UserExample {
    protectedStringorderByClause;

    protected boolean distinct;

    protected ListoredCriteria;

    public UserExample() {
        oredCriteria=newArrayList();
    }

    public voidsetOrderByClause(String orderByClause) {
        this.orderByClause= orderByClause;
    }

    publicStringgetOrderByClause() {
        returnorderByClause;
    }

    public voidsetDistinct(booleandistinct) {
        this.distinct= distinct;
    }

    public booleanisDistinct() {
        returndistinct;
    }

    publicListgetOredCriteria() {
        returnoredCriteria;
    }

    public voidor(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    publicCriteriaor() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    publicCriteriacreateCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() ==0) {
            oredCriteria.add(criteria);
        }
        returncriteria;
    }

    protectedCriteriacreateCriteriaInternal() {
        Criteria criteria = newCriteria();
        return criteria;
    }

    public voidclear() {
        oredCriteria.clear();
        orderByClause=null;
        distinct=false;
    }

    protected abstract static classGeneratedCriteria {
        protectedListcriteria;

        protected GeneratedCriteria() {
            super();
            criteria=newArrayList();
        }

        public booleanisValid() {
            returncriteria.size() >0;
        }

        publicListgetAllCriteria() {
            returncriteria;
        }

        publicListgetCriteria() {
            returncriteria;
        }

        protected voidaddCriterion(String condition) {
            if(condition ==null) {
                throw newRuntimeException("Value for condition cannot be null");
            }
            criteria.add(newCriterion(condition));
        }

        protected voidaddCriterion(String condition,Object value,String property) {
            if(value ==null) {
                throw newRuntimeException("Value for "+ property + " cannot be null");
            }
            criteria.add(newCriterion(condition,value));
        }

        protected voidaddCriterion(String condition,Object value1,Object value2,String property) {
            if(value1 ==null|| value2 ==null) {
                throw newRuntimeException("Between values for "+ property + " cannot be null");
            }
            criteria.add(newCriterion(condition,value1,value2));
        }

        publicCriteriaandIdIsNull() {
            addCriterion("id is null");
            return (Criteria)this;
        }

        publicCriteriaandIdIsNotNull() {
            addCriterion("id is not null");
            return (Criteria)this;
        }

        publicCriteriaandIdEqualTo(Integer value) {
            addCriterion("id =",value,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdNotEqualTo(Integer value) {
            addCriterion("id <>",value,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdGreaterThan(Integer value) {
            addCriterion("id >",value,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("id >=",value,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdLessThan(Integer value) {
            addCriterion("id <",value,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdLessThanOrEqualTo(Integer value) {
            addCriterion("id <=",value,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdIn(List values) {
            addCriterion("id in",values,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdNotIn(List values) {
            addCriterion("id not in",values,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdBetween(Integer value1,Integer value2) {
            addCriterion("id between",value1,value2,"id");
            return (Criteria)this;
        }

        publicCriteriaandIdNotBetween(Integer value1,Integer value2) {
            addCriterion("id not between",value1,value2,"id");
            return (Criteria)this;
        }

        publicCriteriaandUsernameIsNull() {
            addCriterion("username is null");
            return (Criteria)this;
        }

        publicCriteriaandUsernameIsNotNull() {
            addCriterion("username is not null");
            return (Criteria)this;
        }

        publicCriteriaandUsernameEqualTo(String value) {
            addCriterion("username =",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameNotEqualTo(String value) {
            addCriterion("username <>",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameGreaterThan(String value) {
            addCriterion("username >",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameGreaterThanOrEqualTo(String value) {
            addCriterion("username >=",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameLessThan(String value) {
            addCriterion("username <",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameLessThanOrEqualTo(String value) {
            addCriterion("username <=",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameLike(String value) {
            addCriterion("username like",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameNotLike(String value) {
            addCriterion("username not like",value,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameIn(List values) {
            addCriterion("username in",values,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameNotIn(List values) {
            addCriterion("username not in",values,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameBetween(String value1,String value2) {
            addCriterion("username between",value1,value2,"username");
            return (Criteria)this;
        }

        publicCriteriaandUsernameNotBetween(String value1,String value2) {
            addCriterion("username not between",value1,value2,"username");
            return (Criteria)this;
        }

        publicCriteriaandPasswordIsNull() {
            addCriterion("password is null");
            return (Criteria)this;
        }

        publicCriteriaandPasswordIsNotNull() {
            addCriterion("password is not null");
            return (Criteria)this;
        }

        publicCriteriaandPasswordEqualTo(String value) {
            addCriterion("password =",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordNotEqualTo(String value) {
            addCriterion("password <>",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordGreaterThan(String value) {
            addCriterion("password >",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordGreaterThanOrEqualTo(String value) {
            addCriterion("password >=",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordLessThan(String value) {
            addCriterion("password <",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordLessThanOrEqualTo(String value) {
            addCriterion("password <=",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordLike(String value) {
            addCriterion("password like",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordNotLike(String value) {
            addCriterion("password not like",value,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordIn(List values) {
            addCriterion("password in",values,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordNotIn(List values) {
            addCriterion("password not in",values,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordBetween(String value1,String value2) {
            addCriterion("password between",value1,value2,"password");
            return (Criteria)this;
        }

        publicCriteriaandPasswordNotBetween(String value1,String value2) {
            addCriterion("password not between",value1,value2,"password");
            return (Criteria)this;
        }
    }

    public static classCriteriaextendsGeneratedCriteria {

        protectedCriteria() {
            super();
        }
    }

    public static classCriterion {
        privateStringcondition;

        private Objectvalue;

        private ObjectsecondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private StringtypeHandler;

        public StringgetCondition() {
            returncondition;
        }

        publicObjectgetValue() {
            returnvalue;
        }

        publicObjectgetSecondValue() {
            returnsecondValue;
        }

        public booleanisNoValue() {
            returnnoValue;
        }

        public booleanisSingleValue() {
            returnsingleValue;
        }

        public booleanisBetweenValue() {
            returnbetweenValue;
        }

        public booleanisListValue() {
            returnlistValue;
        }

        publicStringgetTypeHandler() {
            returntypeHandler;
        }

        protectedCriterion(String condition) {
            super();
            this.condition= condition;
            this.typeHandler=null;
            this.noValue=true;
        }

        protectedCriterion(String condition,Object value,String typeHandler) {
            super();
            this.condition= condition;
            this.value= value;
            this.typeHandler= typeHandler;
            if (valueinstanceofList) {
                this.listValue=true;
            }else{
                this.singleValue=true;
            }
        }

        protectedCriterion(String condition,Object value) {
            this(condition,value, null);
        }

        protectedCriterion(String condition,Object value,Object secondValue,String typeHandler) {
            super();
            this.condition= condition;
            this.value= value;
            this.secondValue= secondValue;
            this.typeHandler= typeHandler;
            this.betweenValue=true;
        }

        protectedCriterion(String condition,Object value,Object secondValue) {
            this(condition,value,secondValue, null);
        }
    }
}

UserService

package com.demo.service;

import com.demo.pojo.User;

import java.util.List;

public interface UserService {
    List getAll();

    ListgetPage(intpageSize,intpageNo);

    ListgetCondition(String name);

    int insert(String userName,String password);

    int updateUser(intid);
}

 

UserServiceImpl

package com.demo.service.impl;

import com.demo.mapper.UserMapper;
import com.demo.pojo.User;
import com.demo.pojo.UserExample;
import com.demo.service.UserService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImplimplementsUserService {

    @Autowired
    UserMapperuserMapper;

    @Override
    publicListgetAll() {
        UserExample userExample = new UserExample();
        userExample.setDistinct(true);
        return userMapper.selectByExample(userExample);
    }

    @Override
    publicListgetPage(intpageSize,intpageNo) {
        RowBounds rowBounds = new RowBounds(pageNo,pageSize);
        UserExample userExample =newUserExample();
        userExample.setDistinct(true);
         return userMapper.selectByExampleWithBounds(userExample,rowBounds);
    }

    @Override
    publicListgetCondition(String name) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(name);
        return userMapper.selectByExample(userExample);
    }

    @Override
    public intinsert(String userName,String password) {
        User user = newUser();
        user.setUsername(userName);
        user.setPassword(password);
        return userMapper.insert(user);
    }

    @Override
    public intupdateUser(intid) {
        User user = newUser();
        user.setId(id);
        user.setUsername("修改");
        user.setPassword("111");
        return userMapper.updateByPrimaryKey(user);
    }
}

UserController

package com.demo.web;

import com.demo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserServiceuserServiceImpl;

    /**
     * 查询
     *
@return
     
*/
    
@RequestMapping(value="/demo",method= RequestMethod.GET)
    @ResponseBody
    publicObjectgetUsers(){
        returnuserServiceImpl.getAll();
    }

    /**
     * 利用mybatis的rowbounds分页类,分页查询
     */
    
@RequestMapping(value="/page",method= RequestMethod.GET)
    @ResponseBody
    publicObjectgetPage(@RequestParam(name="pageSize") String pageSize,
                            @RequestParam(name="pageNo") String pageNo){
        try{
            String size = pageSize;
            int pageSizes=5,nos=1;
            if(StringUtils.isNotBlank(size)){
                pageSizes = Integer.parseInt(pageSize);
            }
            String no = pageNo;
            if(StringUtils.isNotBlank(no)){
                nos = Integer.parseInt(no);
            }
            returnuserServiceImpl.getPage(pageSizes,nos);
        }catch(Exception ex){
            ex.getMessage();
        }
        return null;
    }

    /**
     * 按条件查询
     */
    
@RequestMapping(value="/condition/{name}",method= RequestMethod.GET)
    @ResponseBody
    publicObjectgetCondition(@PathVariableString name){
        returnuserServiceImpl.getCondition(name);
    }

    /**
     * 增加user
     */
    
@RequestMapping(value="/save",method= RequestMethod.GET)
    @ResponseBody
    publicObjectsave(@RequestParam(name="username") String username,
                               @RequestParam(name="password") String password){
        returnuserServiceImpl.insert(username,password);
    }
    /**
     * 根据id修改user
     */
    
@RequestMapping(value="/update/{id}",method= RequestMethod.GET)
    @ResponseBody
    publicObjectupdateUser(@PathVariableintid){
        returnuserServiceImpl.updateUser(id);
    }

}

demoApplication

package com.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@MapperScan(basePackages= {"com.demo.mapper"})
@ComponentScan(basePackages= {"com.demo"})
@EnableScheduling
@SpringBootApplication
public class DemoApplication {

   public static voidmain(String[] args) {
      SpringApplication.run(DemoApplication.class,args);
   }
}

Application.properties

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM t_user
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=true
spring.datasource.druid.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.druid.useGlobalDataSourceStat=true
#mybatis.mapperLocations=classpath:mybatis/*.xml

GeneratorConfig.xml

xml version="1.0"encoding="UTF-8"?>
generatorConfiguration
        PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


    
    location="D:\maven\repository\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar"/>
    id="testTables"targetRuntime="MyBatis3">
        
            
            name="suppressAllComments"value="true"/>
        
        
        driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"userId="root"
                        password="123">
        
        
        
            name="forceBigDecimals"value="false"/>
        

        
        targetPackage="com.demo.pojo"
                            targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
            
            name="trimStrings"value="true"/>
        
        
        targetPackage="com.demo.mapper"
                         targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
        
        
        type="XMLMAPPER"
                             targetPackage="com.demo.mapper"
                             targetProject="src/main/java">
            
            name="enableSubPackages"value="false"/>
        
        
        schema=""tableName="user">
        
    

Logback.xml

xml version="1.0"encoding="UTF-8"?>
debug="false">
   
   name="LOG_HOME"value="/workspace/example"/>
   
   name="STDOUT"class="ch.qos.logback.core.ConsoleAppender">
      class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
         
         %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
      

   
   
   name="DAYINFO"  class="ch.qos.logback.core.rolling.RollingFileAppender">
      class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
         
         ${LOG_HOME}/TestSpringBoot_info.log.%d{yyyy-MM-dd}.log
         
         30
      

      
      class="ch.qos.logback.classic.filter.LevelFilter">
         info
         ACCEPT
         DENY
      
      class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
         
         %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
      

      
      class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
         10MB
      
   

   
   name="DAYERROR"  class="ch.qos.logback.core.rolling.RollingFileAppender">
      class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
         
         ${LOG_HOME}/TestSpringBoot_error.log.%d{yyyy-MM-dd}.log
         
         30
      

      
      class="ch.qos.logback.classic.filter.LevelFilter">
         error
         ACCEPT
         DENY
      
      class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
         
         %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
      

      
      class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
         10MB
      
   

   
   level="INFO">
      ref="STDOUT"/>
      ref="DAYINFO"/>
      ref="DAYERROR"/>
   

 

 

 

 

Pom.xml

xml version="1.0"encoding="UTF-8"?>
xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   4.0.0

   com
   demo
   0.0.1-SNAPSHOT
   jar

   demo
   Demo project for Spring Boot

   
      org.springframework.boot
      spring-boot-starter-parent
      1.5.10.RELEASE
      
   

   
      UTF-8
      UTF-8
      1.8
   

   
      
         org.springframework.boot
         spring-boot-starter
      

      
         org.springframework.boot
         spring-boot-starter-test
         test
      

      
         org.apache.commons
         commons-lang3
         3.7
      

      
         org.springframework.boot
         spring-boot-starter-web
      

      
         org.springframework.boot
         spring-boot-starter-logging
      

      
      
         com.alibaba
         fastjson
         1.2.46
      

      
         com.alibaba
         druid-spring-boot-starter
         1.1.6
      

      
         org.mybatis.spring.boot
         mybatis-spring-boot-starter
         1.1.1
      

      
         mysql
         mysql-connector-java
         5.1.35
      

   

   
      
         
            org.springframework.boot
            spring-boot-maven-plugin
         
         
            org.mybatis.generator
            mybatis-generator-maven-plugin
            1.3.2
            
               
               src/main/resources/generatorConfig.xml
               true
               true
            
            
               
                  Generate MyBatis Artifacts
                  
                     generate
                  
               
            
            
               
                  org.mybatis.generator
                  mybatis-generator-core
                  1.3.2
               
            
         
      
      
         
            src/main/java
            
               **/*.xml
            
            true
         
      
   


 

八 整合swagger

8.1添加pom.xml依赖


   io.springfox
   springfox-swagger2
   2.2.2



   io.springfox
   springfox-swagger-ui
   2.2.2

8.2UserController添加注解

@Api("测试swagger")
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userServiceImpl;

    /**
     * 查询
     *
@return
     
*/
    
@ApiOperation("查询")
    @RequestMapping(value = "/demo",method = RequestMethod.GET)
    @ResponseBody
    public Object getUsers(){
        return userServiceImpl.getAll();
    }

    /**
     * 利用mybatis的rowbounds分页类,分页查询
     */
    
@ApiOperation("利用mybatis的rowbounds分页类,分页查询")
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    @ResponseBody
    public Object getPage(@RequestParam(name = "pageSize") String pageSize,
                            @RequestParam(name = "pageNo") String pageNo){
        try{
            String size = pageSize;
            int pageSizes=0,nos=0;
            if(StringUtils.isNotBlank(size)){
                pageSizes = Integer.parseInt(pageSize);
            }
            String no = pageNo;
            if(StringUtils.isNotBlank(no)){
                nos = Integer.parseInt(no);
            }
            return userServiceImpl.getPage(pageSizes,nos);
        }catch (Exception ex){
            ex.getMessage();
        }
        return null;
    }

8.3,启动项目,访问http://localhost:8080/swagger-ui.html#/

 

九.整合redis

9.1pom.xml文件加入依赖



   redis.clients
   jedis

9.2 application.properties加入redis配置,前提要有redis服务

#连超时设置
default.redis.timeout=15000
#是否使用连接池
default.redis.usePool = true
#host&port
default.redis.nodes=192.168.0.208:7000

9.3 添加几个类

 spring boot 整合mybatis,swagger,redis,guava等,以及idea自动生成mapper文件_第6张图片

JedisConfig配置类如下

package com.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class JedisConfig {
    @Autowired
    Environment evn;

    @Bean
    public ShardedJedisPool shardedJedisPool(){
        String servers = evn.getProperty("default.redis.nodes");
        int timeOut = Integer.parseInt(evn.getProperty("default.redis.timeout"));
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(2);
        List jedisShardInfos = new ArrayList<>(1);
        String[] split = servers.split(":");
        JedisShardInfo jedisShardInfo = new JedisShardInfo(split[0],Integer.parseInt(split[1]),timeOut);
        jedisShardInfos.add(jedisShardInfo);
        return new ShardedJedisPool(config,jedisShardInfos);
    }
}

redisUtils类如下

package com.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.List;

@Component
public class RedisUtil {
    @Autowired
    ShardedJedisPool pool;

    public void set(String key,String value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = pool.getResource();
            if (shardedJedis != null) {
                shardedJedis.set(key, value);
            }
        } catch (Exception ex) {
        } finally {
            if (shardedJedis != null) {
                shardedJedis.close();
            }
        }
    }

    public String get(String key){
        ShardedJedis shardedJedis = null;
        try{
            shardedJedis = pool.getResource();
            if (shardedJedis != null){
                return shardedJedis.get(key);
            }
        }catch (Exception ex){

        }finally {
            if(shardedJedis != null){
                shardedJedis.close();
            }
        }
        return "1564";
    }

    public List getList(String key){
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = pool.getResource();
            if (shardedJedis != null) {
             return shardedJedis.hmget(key);
            }
        } catch (Exception ex) {
        } finally {
            if (shardedJedis != null) {
                shardedJedis.close();
            }
        }
        return null;
    }

    public void setList(String key,String value){
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = pool.getResource();
            if (shardedJedis != null) {
                shardedJedis.set(key,value);
            }
        } catch (Exception ex) {
        } finally {
            if (shardedJedis != null) {
                shardedJedis.close();
            }
        }
    }

}

常量前缀如下

package com.demo.redis;

public class DbAndCacheContants {
    public static final String USER_CACHE_PREFIX = "user:";
}

 

UserServiceImpl类修改如下代码

@Override
public String getCondition(String name) {
    String redisName = DbAndCacheContants.USER_CACHE_PREFIX + name;
    String str = redisUtil.get(redisName);
    if (StringUtils.isNotBlank(str)){
        return redisUtil.get(redisName);
    }else {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(name);
        List users = userMapper.selectByExample(userExample);
        String value = JSONObject.toJSONString(users);
        redisUtil.set(redisName,value);
        return value;
    }
}

9.4  启动项目,swagger请求,断点调试可以看到第二次从redis里取数据

十.使用本地缓存

10.1 spring boot本身有添加googleguava包,如果没有,pom.xml添加如下依赖


   
      com.google.guava
      guava
      14.0.1
   

 

10.2 UserServiceImpl类添加如下代码

@Override
public User selectByPrimaryKey(Integer id) {
    User user = null;
    try{
        user = userCache.get(id);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return user;
}

//使用本地缓存
LoadingCache,User> userCache = CacheBuilder.newBuilder()
        .expireAfterWrite(2, TimeUnit.MINUTES)//缓存时间20分钟
        .maximumSize(1000)//缓存对象1000个
        .build(new CacheLoader, User>() {
            @Override
            public User load(Integer id) throws Exception {
                User user = userMapper.selectByPrimaryKey(id);
                if(user == null){
                    user = new User();
                }
                return user;
            }
        });

 

UserService接口添加如下方法

User selectByPrimaryKey(Integer id);

UserController添加如下代码

/**
 * 根据id获得user
 */
@ApiOperation("根据id获得user")
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
@ResponseBody
public Object getUser(@PathVariable int id){
    return userServiceImpl.selectByPrimaryKey(id);
}

 

10.3启动项目,断点调试,第二次不在访问数据库,使用了本地缓存

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


你可能感兴趣的:(后端,java,springboot,idea)