SpringBoot special study Part21: SpringBoot integration MyBatis configuration and use - Profiles achieve

First introduced depend on:

<!-- Druid数据源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

<!-- 日志转换包 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>log4j-over-slf4j</artifactId>
    <version>1.7.25</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Then configure the data source
I use is Druid data source

yml profile:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot_mybatis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    username: root
    password: 123456
    initialization-mode: always
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Then create a configuration category to configure Druid:

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid()
    {
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean statViewServlet()
    {
        ServletRegistrationBean<StatViewServlet> srb = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        // 设置初始化参数
        Map<String,String> initParams=new HashMap<>();
        // 登录后台的用户名
        initParams.put("loginUsername","admin");
        // 登录后台的密码
        initParams.put("loginPassword","123456");
        // 允许访问的ip 默认或为空代表允许所有
        initParams.put("allow","");
        // 不允许访问的ip
        initParams.put("deny","111.111.111.111");
        srb.setInitParameters(initParams);
        return srb;
    }

    @Bean
    public FilterRegistrationBean webStatFilter()
    {
        FilterRegistrationBean<Filter> frb = new FilterRegistrationBean<>();
        // 传入Druid的监控Filter
        frb.setFilter(new WebStatFilter());
        // 设置初始化参数
        Map<String,String> initParams=new HashMap<>();
        // 设置哪些路径不进行拦截
        initParams.put("exclusions","*.js,*.css,/druid/*");
        frb.setInitParameters(initParams);
        // 设置拦截的请求
        frb.setUrlPatterns(Arrays.asList("/*"));
        return frb;
    }
}

Create a data table and the corresponding bean class
and then you can begin to configure:

First, write an interface:
the interface which defines the curd To operate the database
if not add @MapperScan notes shall be added to the interface class @Mapper

public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);

    public void insertEmployee(Employee employee);
}

After you configure MyBatis the global configuration file :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

Which is empty because the global configuration file is typically used to configure the data source
and the data source above has a good job of the Druid

After also need to configure the SQL Map configuration file :
mapping configuration file in the resources directory resource
name is usually taken to xxxMapper.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">
<mapper namespace="net.zjitc.springboot.mapper.EmployeeMapper">
    <select id="getEmployeeById" resultType="net.zjitc.springboot.bean.Employee">
        select * from employee where id=#{id}
    </select>

    <insert id="insertEmployee">
        insert into employee(lastName,email,gender,d_id) values(#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

Yml also needs to be configured in the configuration file (properties configuration file syntax is also OK but not the same
configuration purposes is to let MyBatis aware of the existence of these configuration files:

mybatis:
  # MyBatis全局配置文件的路径
  config-location: classpath:mybatis/mybatis-config.xml
  # MyBatis映射配置文件的路径
  mapper-locations: classpath:mybatis/mapper/*.xml

This configuration is over

Simple test:

@RestController
public class EmployeeController {

    @Autowired
    EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmployee(@PathVariable("id") Integer id)
    {
        return employeeMapper.getEmployeeById(id);
    }
}

Here Insert Picture Description
Test success


When the value of the database field and inconsistent bean property is acquired null
can configure hump map

MyBatis is configured in the global configuration file:

<settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

Notes version of MyBatis MyBatis version and configuration files can coexist mix


Published 174 original articles · won praise 5 · Views 240,000 +

Guess you like

Origin blog.csdn.net/Piconjo/article/details/105096658