Spring Boot 2.1.3 集成 MyBatis + Druid

Spring Boot 集成 MyBatis + Druid 快速开发

  • Spring Boot 简介
  • 集成SpringBoot + MyBatis + Druid 开发环境
    • 项目依赖
    • 配置文件
    • Druid连接池集成
    • 测试集成结果

Spring Boot 简介

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。

该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

通过这种方式,Spring Boot 致力于在蓬勃发展的快速应用开发领域(rapidapplication development)成为领导者。

集成SpringBoot + MyBatis + Druid 开发环境

项目依赖

SpringBoot的Maven依赖如下,这里我选择的SpringBoot版本为当前最新版 2.1.3
	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-thymeleafartifactId>
	dependency>
	
	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-webartifactId>
	dependency>
	
	
	<dependency>
		<groupId>org.mybatis.spring.bootgroupId>
		<artifactId>mybatis-spring-boot-starterartifactId>
		<version>2.0.0version>
	dependency>

	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-devtoolsartifactId>
		<scope>runtimescope>
	dependency>
	
	
	<dependency>
		<groupId>mysqlgroupId>
		<artifactId>mysql-connector-javaartifactId>
		<scope>runtimescope>
	dependency>
	
	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-testartifactId>
		<scope>testscope>
	dependency>
	
	
	<dependency>
		<groupId>com.alibabagroupId>
		<artifactId>druid-spring-boot-starterartifactId>
		<version>1.1.10version>
	dependency>

	
	<dependency>
		<groupId>org.apache.commonsgroupId>
		<artifactId>commons-lang3artifactId>
	dependency>

配置文件

由于使用了SpringBoot,所以大部分不需要我们手动配置,只需要进行简单的指定数据源等必要的配置,yml文件配置信息如下

spring:
  #开发时关闭页面缓存,不然无法看到实时页面
  thymeleaf:
    cache: false  
    
  #配置Druid数据源
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    platform: mysql
    druid: 
      initial-size: 5  # 初始化大小
      min-idle: 5  # 最小
      max-active: 100  # 最大
      max-wait: 60000  # 连接超时时间
      time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      min-evictable-idle-time-millis: 300000  # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒
      validationQuery: SELECT 'x'
      test-while-idle: true  # 当连接空闲时,是否执行连接测试
      test-on-borrow: false  # 当从连接池借用连接时,是否测试该连接
      test-on-return: false  # 在连接归还到连接池时是否测试该连接
      filters: config,wall,stat  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      maxOpenPreparedStatements: 20
      connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=true
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
        session-stat-enable: true
        session-stat-max-count: 10
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        login-username: admin
        login-password: 123
        
#MyBatis配置
mybatis:
  mapper-locations: classpath:mapper/**/*.xml   #配置Mapper.xml文件所在路径
  type-aliases-package: com.demo.pojo   #配置别名

这里我将MyBatis 的 Mapper.xml 文件放在了 src/main/resources/ 下
Spring Boot 2.1.3 集成 MyBatis + Druid_第1张图片

Druid连接池集成

集成Druid连接池的Java代码如下:

package com.demo.config;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

/**
 * Druid数据源配置
 * @author 码农小七
 */
@Configuration	//此注解标注此Java类为一个配置类
public class DruidConfig {

	@Bean
	@Primary
	@ConfigurationProperties("spring.datasource")
	public DataSource dataSource() {
		return DruidDataSourceBuilder.create().build();
	}
}

至此,我们的集成已经差不多结束了,但是还缺少一项,我们在SSM中需要扫描MyBatis的Mapper接口所在的包,产生对应的动态代理对象。在SpringBoot中也需要如此,我们需要在SpringBoot的主启动类中加入@MapperScan注解,否则会报自动装配失败的错误异常,代码如下:

package com.demo;

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

@MapperScan("com.demo.mapper")	//扫描Mapper接口所在的包,产生与之对应的动态代理对象
@SpringBootApplication
public class SpringbootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootDemoApplication.class, args);
	}

}

测试集成结果

现在,我们已经把集成工作完成,开始测试我们的代码吧!

实体类代码如下:

package com.demo.pojo;

public class User {

	private Integer id;
	private String userName;
	private String passWord;
	private Integer sex;
	private String email;
	private String phone;
	private String birthday;
	private String skill;

	public Integer getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	public Integer getSex() {
		return sex;
	}

	public void setSex(Integer sex) {
		this.sex = sex;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getSkill() {
		return skill;
	}

	public void setSkill(String skill) {
		this.skill = skill;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + ", sex=" + sex + ", email="
				+ email + ", phone=" + phone + ", birthday=" + birthday + ", skill=" + skill + "]";
	}

}

MyBatis Mapper.xml 如下:



<mapper namespace="com.demo.mapper.UserMapper">

	
	<select id="getUsers" parameterType="User" resultType="User">
		select * from `user` 
	select>
	
mapper>

Mapper.xml 对应的接口代码如下:

package com.demo.mapper;

import java.util.List;

import com.demo.pojo.User;

public interface UserMapper {

	List<User> getUsers();
}

Service 层代码如下:

package com.demo.service;

import java.util.List;

import com.demo.pojo.User;

public interface UserService {

	List<User> getUsers();
}

ServiceImpl 实现类代码如下:

package com.demo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.mapper.UserMapper;
import com.demo.pojo.User;
import com.demo.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Override
	public List<User> getUsers() {
		return userMapper.getUsers();
	}
}

接下来我们就可以在测试类中测试我们的代码了:

package com.demo;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.demo.pojo.User;
import com.demo.service.UserService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDemoApplicationTests {
	
	@Autowired
	private UserService userService;

	@Test
	public void contextLoads() {
		List<User> users = userService.getUsers();
		for (User user : users) {
			System.err.println(user);
		}
	}
}

测试结果如下:
测试结果

你可能感兴趣的:(Java)