SpringBoot2.0整合Mybatis+Druid

POM文件


  4.0.0
  com.arusi.innofarm
  SpringBoot
  0.0.1-SNAPSHOT
  war
  
    UTF-8
       1.7
  
    
          
        org.springframework.boot  
        spring-boot-starter-parent  
        2.0.3.RELEASE 
    
    
         
        
          org.springframework.boot  
          spring-boot-starter-web  
      
       
            mysql  
            mysql-connector-java  
            runtime  
      
     
        
            com.alibaba
            druid
            1.0.28
        
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.1.1
     
  
   
       
        
          
               org.springframework.boot
               spring-boot-maven-plugin
               
                    UTF-8
                
                
                  
                  
                     org.springframework 
                     springloaded 
                     1.2.4.RELEASE
                  
                
                
                  
                      
                         repackage 
                      
                      
                         exec 
                      
                  
               
              
          
    
  

application.yml配置文件

#开发环境配置
server:
  #端口
  port: 8090
  tomcat:
    uri-encoding: utf-8

#mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.aruisi.ai.dto

#数据库配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true
    username: root
    password: root
    # 初始化大小,最小,最大
    initialSize: 1
    minIdle: 3
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 30000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    #useGlobalDataSourceStat: true

DDL文件

CREATE TABLE `sys_user` (
  `userId` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

UserMapper.xml






    
        select
               userId,username,password
        from sys_user where username=#{username}
    

IUserDAO

这里没有使用@Mapper

package com.aruisi.ai.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.aruisi.ai.dto.UserDTO;
public interface IUserDAO {
    public UserDTO selectByUserName(@Param("username") String userName);
}

UserService

package com.aruisi.ai.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aruisi.ai.dao.IUserDAO;
import com.aruisi.ai.dto.UserDTO;
@Service
public class UserService {
    @Autowired
    private IUserDAO userMapper;
    public UserDTO selectByUserName(String username) {
        UserDTO users = userMapper.selectByUserName(username);
        return users;
    }
}

Druid配置类

package com.aruisi.ai.config;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
@SuppressWarnings("all")
@Configuration
public class DruidConfig {
    private static final Logger log = LoggerFactory
            .getLogger(DruidConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

    @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(initMethod = "init", destroyMethod = "close")
    @Primary
    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) {
            log.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);
        return datasource;
    }

    /**
     * 
     * http://127.0.0.1:8090/monitor/druid/login.html
     * 
     * @Title: druidServlet
     * @Description: 注册一个StatViewServlet 相当于在web.xml中声明了一个servlet
     * @param: void
     * @return: ServletRegistrationBean
     * @throws
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/monitor/druid/*");
        /** 白名单 */
        reg.addInitParameter("allow", "127.0.0.1");
        /** IP黑名单(共同存在时,deny优先于allow) */
        // reg.addInitParameter("deny", "192.168.2.105");
        /** /druid/login.html登录时账号密码 */
        reg.addInitParameter("loginUsername", "root");
        reg.addInitParameter("loginPassword", "root");
        /** 是否能够重置数据 禁用HTML页面上的“Reset All”功能 */
        reg.addInitParameter("resetEnable", "false");
        return reg;
    }

    /**
     * 注册一个:filterRegistrationBean 相当于在web.xml中声明了一个Filter
     */
    @Bean
    public FilterRegistrationBean druidStatFilter() {
        FilterRegistrationBean druidStatFilter = new FilterRegistrationBean();
        druidStatFilter.setFilter(new WebStatFilter());
        /** 添加过滤规则. */
        druidStatFilter.addUrlPatterns("/*");
        /** 监控选项滤器 */
        druidStatFilter.addInitParameter("DruidWebStatFilter", "/*");
        /** 添加不需要忽略的格式信息. */
        druidStatFilter.addInitParameter("exclusions",
                "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/monitor/druid/*");
        /** 配置profileEnable能够监控单个url调用的sql列表 */
        druidStatFilter.addInitParameter("profileEnable", "true");
        /** 当前的cookie的用户 */
        druidStatFilter.addInitParameter("principalCookieName", "USER_COOKIE");
        /** 当前的session的用户 */
        druidStatFilter
                .addInitParameter("principalSessionName", "USER_SESSION");
        return druidStatFilter;
    }
}

UserController类

package com.aruisi.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.aruisi.ai.dto.UserDTO;
import com.aruisi.ai.service.UserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/getUser")
    @ResponseBody
    public UserDTO getUser() {
        UserDTO userName = userService.selectByUserName("admin");
        return userName;
    }
}

主函数

@MapperScan("com.aruisi.ai.dao")加上这个注解,就不用在每个dao类上加@Mapper注解

package com.aruisi;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.aruisi.ai.dao")
public class XiYueApplication {
    public static void main(String[] args) {
        SpringApplication.run(XiYueApplication.class, args);
    }
}

访问druid监控页面

访问链接:http://127.0.0.1:8090/monitor/druid/login.html 输入账号,密码

你可能感兴趣的:(SpringBoot)