【spring boot2】第9篇:spring boot 整合 mybatis

引入starter

修改pom.xml文件,整合mybatis須要以下的包css

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!--mybatis的starter-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>

<!--mysql驅動-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!--druid鏈接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

durid鏈接池配置

修改yml文件

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/sff_test
    driver-class-name: com.mysql.jdbc.Driver
    # 指定本身使用的數據源
    type: com.alibaba.druid.pool.DruidDataSource

    # DruidDataSource 其餘屬性配置
    druid:
     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
     maxPoolPreparedStatementPerConnectionSize: 20
     useGlobalDataSourceStat: true
     filter:
      stat:
       enabled: true
       log-slow-sql: true
      wall:
       enabled: true

注入duird配置

@Configurable
public class DruidConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.druid")
    public DataSource dataSourceTwo() {
        return DruidDataSourceBuilder.create().build();
    }
    /**
     * 配置一個管理後臺的Servlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<>();

        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "admin");
        initParams.put("allow", "");//默認就是容許全部訪問

        bean.setInitParameters(initParams);
        return bean;
    }
    /**
     * 配置一個web監控的filter
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParams = new HashMap<>();
        //經過 localhost:8080/druid/ 能夠訪問到監控後臺
        initParams.put("exclusions", "*.js,*.css,/druid/*");

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

        return bean;
    }
}

配置mybatis組件

使用mybatis註解

定義mapper接口

@Mapper
public interface DeptMapper {

    @Select("select * from dept")
    List<Dept> selectAll();
}

注入mybatis相關配置

public class MybatisConfig {

    //定製mybatis配置
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                //開啓駝峯命令
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}
  1. 開啓駝峯命名,若是不開啓會致使數據庫中的這種dept_name等字段沒法轉換爲bean中的deptName字段
  2. 在咱們的mapper接口不少的時候,好比說有多個相似 DeptMapper時,若是每一個mapper都寫@Mapper註解很麻煩,此時能夠在MybatisConfig配置類上使用@MapperScan(value = "com.sff.spring.boot.mybatis.dao")這個註解,去掉@Mapper註解便可

使用mapper.xml文件

定義mapper接口

public interface EmpMapper {
    List<Emp> selectAll();
}

定義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">
<mapper namespace="com.sff.spring.boot.mybatis.dao.EmpMapper">
    <select id="selectAll" resultType="Emp">
        select * from emp
    </select>
</mapper>

注意:使用mapper的xml文件時,記得將mapper接口注入的容器中,使用@Mapper`或者@MapperScan註解 html

定義mybatis的全局配置文件

<?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>
    <settings>
        <!--開啓駝峯命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <!--實體bean路徑-->
        <package name="com.sff.spring.boot.mybatis.domain"/>
    </typeAliases>
</configuration>

修改yml文件,指定mybatis配置、mapper文件路徑

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  config-location: classpath:mybatis/mybatis-config.xml

自定義starter

其餘參考

相關文章
相關標籤/搜索