Integration of data sources and SpringBoot Druid frame Mybatis

Druid Ali developed with data from monitoring is recommended!

在pom文件中引入依赖
 <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!-- 因为druidj中配置了lo4j的日志功能,所以需要引入log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

Our data source configuration file in application.yml

server:
  port: 8888

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp&useSSL=false&amp&characterEncoding=UTF-8&amp&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters , stat:监控统计、wall:防止SQL注入、log4j:日志记录
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Configuring a DruidConfig class configuration of our Druid data sources used to customize the (dead code does not need to remember directly on the line)

package com.jee.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }
    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

We went to look at Druid's web page monitoring page
Here Insert Picture Description
to enter a user name and password we'll configuration class set to sign:
Here Insert Picture Description

Above our Druid data source on the configuration finished

After configuring the data source we have is very simple to configure Mybatis framework

First import dependence:

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

Create a database table and the corresponding entity class

public class User {
    private int id;
    private String name;
    private String password;

    public User() {
    }
}

Create a mapper class

@Mapper   //@Mapper注解表示这个接口是Mybatis中的Mapper类
@Repository  //@Repository注解表示这个类是输入dao层的
public interface UserMapper {
    //查找所有用户
    public List<User> getAllUser();
}

Create a directory next to the resource mybatis/mapperdirectory for storing files mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <!--注意  这里我们的resultType用了别名 而不是全类名  这是我们再application.yml中配置的 我们待会就去配置-->
<mapper namespace="com.jee.mapper.UserMapper">
    <select id="selectAllUser" resultType="User">
         select * from user
    </select>
</mapper>

Finally go application.yml configured in some of our mybatis

mybatis:
  type-aliases-package: com.jee.entity   #起别名的包  该包下所有的类都会自动设置别名 就是类本身的名字
  mapper-locations: classpath:mybatis/mapper/*Mapper.xml  #mapper.xml文件的存放位置

When we use the mapper interfaces can be automatically injected into the code

@Controller
public class MyController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/aa")
    @ResponseBody
    public String fun1() throws JsonProcessingException {
        List<User> allUser = userMapper.getAllUser();
        ObjectMapper mapper = new ObjectMapper();
        return (mapper.writeValueAsString(allUser));
    }
}
Published 53 original articles · won praise 0 · Views 1944

Guess you like

Origin blog.csdn.net/XXuan_/article/details/104848531