1. 程式人生 > >SpringBoot配置Druid資料來源,持久層分別 mybatis,jdbc

SpringBoot配置Druid資料來源,持久層分別 mybatis,jdbc

Druid與mybatis整合:

application.yaml 配置引數檔案

spring:
  datasource:
    #driver-class-name: com.mysql.jdbc.Driver
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/activiti10unit?characterEncoding=utf-8&serverTimezone=GMT
    username: root
    password: root
    #告知springboot 使用的連結池型別是druid
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 20
    maxActive: 30
    minIdle: 10
    userSSL: false

提示:

mysql的connecto 驅動 jar 從5.1.33-5.1.37 的TimeUtil類存在bug;

在連線的url後加一個引數 serverTimezone=GMT ,這裡的時區可以根據自己資料庫的設定來設定,

mysql新的安全性設定要求SSL連線,此處可以加一個引數userSSL=false,或者自己設定SSL也可以

另外 6.0.2版本的driverClassName不再是原來的路徑,改成com.mysql.cj.jdbc.Driver了;

否則會報以下錯誤:

WARNING: Unexpected exception resolving reference
java.sql.SQLException: The server timezone value '◇□' is unrecognized or represents more than one timezone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc timezone value if you want to utilize timezone support.

 

com.example.mybatis2018.config.DruidConfig 配置引數類,有些引數必須自己配置載入進容器:

package com.example.mybatis2018.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DruidConfig {

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

 

使用mybatis持久層,寫mapper介面

com.example.mybatis2018.mapper.UserMapper

主鍵版:

package com.example.mybatis2018.mapper;

import com.example.mybatis2018.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

/**
 * 使用@Mapper主鍵 來標註這是一個Mapper介面
 */
@Mapper
public interface UserMapper {
   @Select("select * from user where id = #{id}")
    User selectUserbyId(Long id);
     /**
      * 自增主鍵 select last_insert_id()
      * 非 自增主鍵 select uuid()  before:true
      * @param user
      * @return
      */
    //自增主鍵
    @SelectKey(keyProperty = "id",keyColumn = "id",statement = "select last_insert_id()" ,before=false,resultType = Long.class)
    @Insert("insert into user (USER_NAEM,USER_PASSWORD) values(#{USER_NAEM},#{USER_PASSWORD})")
    int insertUser(User user);
    @Delete("delete from user where id = #{id}")
    int deleteUserById(Long id);
    @Update("update user set USER_NAEM=#{USER_NAEM},USER_PASSWORD = #{USER_PASSWORD} where id = #{id}")
    int updateUser(User user);
}

 

---------------------------------------------------------------------------------------------------------------

Druid與jdbc整合:

因為starter-jdbc中自帶HikariCp連線池,需要剔除此連結池,後再加入Druid連線池依賴,後續配置參照上面與mybatis整合的配置一致;

剔除原有連線池依賴

 

加入Druid連線池依賴

後面配置參照與mybatis整合的配置