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整合的配置

猜你喜欢

转载自blog.csdn.net/qq_15204179/article/details/84645278