1. 程式人生 > 其它 >5、SpringBoot連線資料庫引入mybatis

5、SpringBoot連線資料庫引入mybatis

系列導航

1、springboot工程新建(單模組)

2、springboot建立多模組工程

3、springboot連線資料庫

4、SpringBoot連線資料庫引入druid

5、SpringBoot連線資料庫引入mybatis

未完待續

SpringBoot連線資料庫引入mybatis

1、 在上一個專案的基礎上pom.xml增加mybatis的依賴

<?xml version="1.0" encoding="UTF-8"?>
<project 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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name
>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>
UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.1.17.RELEASE</spring-boot.version> </properties> <dependencies> <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>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency> <!-- 整合druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- 整合mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </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> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.17.RELEASE</version> <configuration> <mainClass>com.example.demo.DemoApplication</mainClass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>

2、application.properties配置

 增加mybatis的配置,如下紅色部分

# 應用名稱
spring.application.name=demo
# 應用服務 WEB 訪問埠
server.port=8080

# 資料庫設定
spring.datasource.driverClassName=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@192.168.0.100:1521:orcl
spring.datasource.username=zy
spring.datasource.password=1

# druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# druid引數調優(可選)
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連線等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個連線在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# 測試連線
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 開啟PSCache,並且指定每個連線上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters
spring.datasource.filters=stat
# asyncInit是1.1.4中新增加的配置,如果有initialSize數量較多時,開啟會加快應用啟動時間
spring.datasource.asyncInit=true

## mybatis配置
# 引數型別的包別名設定
mybatis.typeAliasesPackage=com.example.demo.domain
# 指向對映xml檔案目錄
mybatis.mapperLocations=classpath:mapper/*.xml
注:typeAliasesPackage:引數型別的包別名設定,設定這個以後xml對映檔案在parameterType的值就不用寫成全路徑名了,parameterType=”com.example.demo.domain.Block”可以寫成parameterType = “Block”

4、檔案目錄

5、啟動類DemoApplication 上新增 @MapperScan註解

@MapperScan的作用是指定要掃描的mybatis對映類的路徑,放在應用類的前面:



package com.example.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.stereotype.Component;

@SpringBootApplication
//指定要掃描的mybatis對映類的路徑
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

 

6、程式碼部分

DruidConfig的配置類
package com.example.demo.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class DruidConfig {
    private Logger logger = 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.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.initial-size}")
    private int initialSize;

    @Value("${spring.datasource.min-idle}")
    private int minIdle;

    @Value("${spring.datasource.max-active}")
    private int maxActive;

    @Value("${spring.datasource.max-wait}")
    private int maxWait;

    @Value("${spring.datasource.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.min-evictable-idle-time-millis}")
    private int minEvictableIdleTimeMillis;

//    @Value("${spring.datasource.validation-query}")
//    private String validationQuery;

    @Value("${spring.datasource.test-while-idle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.test-on-borrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.test-on-return}")
    private boolean testOnReturn;

    @Value("${spring.datasource.pool-prepared-statements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.max-pool-prepared-statement-per-connection-size}")
    private int maxPoolPreparedStatementPerConnectionSize;

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



    @Bean     //宣告其為Bean例項
    @Primary  //在同樣的DataSource中,首先使用被標註的DataSource
    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) {
            logger.error("druid configuration initialization filter", e);
        }
//      datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
}
Block  實體定義 
package com.example.demo.domain;

 
public class  Block   {
    private String blockId;
 
    private String blockName;

    public String getBlockId() {
        return blockId;
    }

    public void setBlockId(String blockId) {
        this.blockId = blockId;
    }

    public String getBlockName() {
        return blockName;
    }

    public void setBlockName(String blockName) {
        this.blockName = blockName;
    }

    @Override
    public String toString() {
        return "XyDicBlockT{" +
                "blockId='" + blockId + '\'' +
                ", blockName='" + blockName + '\'' +
                '}';
    }
}

 

mapper檔案

package com.example.demo.mapper;

import com.example.demo.domain.Block;
import org.apache.ibatis.annotations.Mapper;


public interface  BlockMapper {
    // 對應xml對映檔案元素的ID
    Block selectByPrimaryKey(String blockId);
}

 

介面類

package com.example.demo.service;

import com.example.demo.domain.Block;

public interface  BlockService {

    Block getUserById(String userId);


}

介面實現類

package com.example.demo.service.impl;


import javax.annotation.Resource;

import com.example.demo.domain.Block;
import com.example.demo.mapper.BlockMapper;
import com.example.demo.service.BlockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
public class BlockServiceImpl implements BlockService {

    // 注入mapper類
    @Autowired
    private BlockMapper blockMapper;

    @Override
    public Block getUserById(String blockId) {
        return blockMapper.selectByPrimaryKey(blockId);
    }
}

 

 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.example.demo.mapper.BlockMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.domain.Block">
        <result property="blockId" column="block_Id"/>
        <result property="blockName" column="block_Name"/>
    </resultMap>

    <sql id="Base_Column_List">
        block_id,block_name
    </sql>
    <select id="selectByPrimaryKey" parameterType="String"  resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from TEST_BLOCK_T
        where block_Id = #{blockId,jdbcType=VARCHAR}
    </select>
</mapper>

 

控制器類

package com.example.demo.controller;


import com.example.demo.domain.Block;
import com.example.demo.service.BlockService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private BlockService blockService;

    @GetMapping("/list")
    @ResponseBody
    public Block index() {

        Block block =  blockService.getUserById("1");

        return block;
    }
}

 

7、啟動專案訪問專案