mybatiesPlus+druidDataSource


title: mybatiesPlus+druidDataSource
date: 2020-02-11 14:20:35
tags:

  • mybaties
  • druidDataSource
    categories:
  • 后端

初学mybatiesPlus时,只为创建一个demo,就遇到了很多问题,在此记录一下。

导入依赖

		<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>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>

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

        <!--mybatis-plus自动的维护了mybatis以及mybatis-spring的依赖,
        在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>

        <!--导入thymeleaf依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

配置 Druid 数据连接池

配置application.properties

	# 服务器端口
	server.port=8096 
	
	# 数据库设置
	spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
	spring.datasource.url=jdbc:mysql://localhost:3306/sanschool?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
	spring.datasource.username=root
	spring.datasource.password=123456
	
	# 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

Durid数据连接池的配置文件 DruidConfig

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

    //    @Value("${spring.datasource.connection-properties}")
    //    private String connectionProperties;

        @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;
        }
    }

配置mybatisPlus

entity

Movie

package com.example.san_two.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

@TableName("movie")
public class Movie implements Serializable {

    @TableId(type = IdType.AUTO)
    int id;
    @TableField
    String title;
    @TableField
    String url;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "Movie{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", url='" + url + '\'' +
                '}';
    }
}


mapper

package com.example.san_two.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.san_two.entity.Movie;
import org.springframework.stereotype.Repository;

@Repository
public interface MovieMapper extends BaseMapper<Movie> {
}

service

MovieService

package com.example.san_two.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.san_two.entity.Movie;

public interface MovieService extends IService<Movie> {
}

MovieServiceImpl


package com.example.san_two.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.san_two.entity.Movie;
import com.example.san_two.mapper.MovieMapper;
import com.example.san_two.service.MovieService;
import org.springframework.stereotype.Service;

@Service
public class MovieServiceImpl extends ServiceImpl<MovieMapper, Movie> implements MovieService {

}

controller

检测druid数据连接池是否连接成功
HelloController


package com.example.san_two.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping(value="/hello", method= RequestMethod.GET)
    public String index() {

        String sql = "SELECT title FROM movie WHERE id = ?";

        // 通过jdbcTemplate查询数据库
        String title = (String)jdbcTemplate.queryForObject(
                sql, new Object[] { 1 }, String.class);

        return "Hello " + title;
    }



}

检测mybatiesPlus是否配置成功
MovieController

package com.example.san_two.controller;

import com.example.san_two.entity.Movie;
import com.example.san_two.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    private MovieService movieService;

    @RequestMapping("/getAll")
    public String getAll() {
        List<Movie> list = movieService.list();
        System.out.println("list:" + list);
        return list.toString();
    }

    @RequestMapping("/insert")
    public String insert() {
        Movie movie = new Movie();
        // 不设置id的话,会自动生成一个UUID
//        user.setId(new Date().getTime() + "");
        movie.setTitle("aaa");
        movie.setUrl("bbb");
        boolean save = movieService.save(movie);
        return getAll();
    }


}

主程序

SanTwoApplication

package com.example.san_two;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.san_two.mapper")
public class SanTwoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SanTwoApplication.class, args);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值