1. 程式人生 > >springboot 整合mybatisPlus

springboot 整合mybatisPlus

今天整理下自己在整合springboot + mybatisPlus 中遇到的一些小挫折。

專案整體結構圖:(請注意:我這裡使用的MYSQL 版本為8)


專案整體依賴的pom 檔案:

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.zzg</groupId>
		<artifactId>springboot</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>springboot-mybatisplus</artifactId>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!--引入swagger -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.2.2</version>
		</dependency>
		<!--整合mybatis -->
		<!-- 與資料庫操作相關的依賴 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!-- 使用資料來源 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.6</version>
		</dependency>

		<!-- mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>

		<!-- mybatisplus整合 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatisplus-spring-boot-starter</artifactId>
			<version>1.0.5</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus</artifactId>
			<version>2.1.8</version>
		</dependency>
		<!-- mybatisplus 程式碼生成器 -->
		<!-- 模板引擎 -->
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-engine-core</artifactId>
			<version>2.0</version>
		</dependency>

		<!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.23</version>
		</dependency>
	</dependencies>

</project>

第一步:整合mybatisplus 核心框架pom.xml

                <!--整合mybatis -->
		<!-- 與資料庫操作相關的依賴 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!-- mybatisplus整合 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatisplus-spring-boot-starter</artifactId>
			<version>1.0.5</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus</artifactId>
			<version>2.1.8</version>
		</dependency>
注意: mybatis-plus 自動的維護了mybatis以及mybatis-spring的依賴,在springboot中這三者不能同時的出現,避免版本的衝突,表示:跳進過這個坑。。。

第二步:整合mybatisplus  程式碼生成器

                <!-- mybatisplus 程式碼生成器 -->
		<!-- 模板引擎 -->
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-engine-core</artifactId>
			<version>2.0</version>
		</dependency>

		<!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.23</version>
		</dependency>

編寫mybatisplus  自動生成器MybatisPlusGenerator.java(基於單列模式進行建立)

package com.zzg.springboot.auto;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class MybatisPlusGenerator {
	private static MybatisPlusGenerator single = null;
	
	private MybatisPlusGenerator() {
		super();
	}
	
	private static MybatisPlusGenerator getSingle() {
		if(single == null) {
			single =new MybatisPlusGenerator();
		}
		return single;
	}
	
	public void autoGeneration() {
		 GlobalConfig config = new GlobalConfig();
	        String dbUrl = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
	        DataSourceConfig dataSourceConfig = new DataSourceConfig();
	        dataSourceConfig.setDbType(DbType.MYSQL)
	                .setUrl(dbUrl)
	                .setUsername("root")
	                .setPassword("123456")
	                .setDriverName("com.mysql.cj.jdbc.Driver");
	        StrategyConfig strategyConfig = new StrategyConfig();
	        strategyConfig
	                .setCapitalMode(true)
	                .setEntityLombokModel(false)
	                .setDbColumnUnderline(true)
	                .setNaming(NamingStrategy.underline_to_camel);
	        config.setActiveRecord(false)
	                .setEnableCache(false)
	                .setAuthor("zzg")
	                //指定輸出資料夾位置
	                .setOutputDir("E:\\workspace\\springboot\\springboot-mybatisplus\\src\\main\\java")
	                .setFileOverride(true)
	                .setServiceName("%sService");
	        new AutoGenerator().setGlobalConfig(config)
	                .setDataSource(dataSourceConfig)
	                .setStrategy(strategyConfig)
	                .setPackageInfo(
	                        new PackageConfig()
	                                .setParent("com.zzg.springboot")
	                                .setController("controller")
	                                .setEntity("entity")
	                ).execute();
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MybatisPlusGenerator generator = MybatisPlusGenerator.getSingle();
		generator.autoGeneration();
	}

}

第三步:配置application.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
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.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.zzg.springboot.entity

第四步:專案的配置資訊

package com.zzg.springboot.config;

import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;

@Configuration
//掃描dao或者是Mapper介面
@MapperScan("com.zzg.springboot.mapper*")
public class MybatisPlusConfig {
	 /***
     * plus 的效能優化
     * @return
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        /*<!-- SQL 執行效能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 -->*/
        performanceInterceptor.setMaxTime(1000);
        /*<!--SQL是否格式化 預設false-->*/
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    /**
     * @Description : mybatis-plus分頁外掛
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    // 配置資料來源
    @Bean(name="dataSource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource(){
        return new DruidDataSource();
    } 

    // 配置事物管理器
    @Bean(name="transactionManager") 
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }
}

第五步:啟動springbootApplication

package com.zzg.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootMybatisPlus {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SpringApplication.run(SpringBootMybatisPlus.class, args);
        System.out.println("============= SpringBoot web Start Success =============");
	}

}

專案關聯的entity層、dao層、service層、controller層和*Mapper.xml檔案

package com.zzg.springboot.entity;

import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import java.io.Serializable;

/**
 * <p>
 * 學員表
 * </p>
 *
 * @author zzg123
 * @since 2018-07-15
 */
public class TStudent implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "sid", type = IdType.AUTO)
    private Integer sid;
    private String sname;
    private String sex;


    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSex() {
        return sex;
    }

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

    @Override
    public String toString() {
        return "TStudent{" +
        ", sid=" + sid +
        ", sname=" + sname +
        ", sex=" + sex +
        "}";
    }
}
package com.zzg.springboot.mapper;

import java.util.Map;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.zzg.springboot.entity.TStudent;

/**
 * <p>
 * 學員表 Mapper 介面
 * </p>
 *
 * @author zzg123
 * @since 2018-07-15
 */
public interface TStudentMapper extends BaseMapper<TStudent> {
	/**
     * 
     * @Title: selectUserByMap
     * @Description: 多條件組合查詢使用者
     * @param userId
     * @return
     * @throws Exception
     */
	TStudent selectUserByMap(Map<String, Object> parameterMap) throws Exception;
}

package com.zzg.springboot.service;

import java.util.Map;

import com.baomidou.mybatisplus.service.IService;
import com.zzg.springboot.entity.TStudent;

/**
 * <p>
 * 學員表 服務類
 * </p>
 *
 * @author zzg123
 * @since 2018-07-15
 */
public interface TStudentService extends IService<TStudent> {
	/**
     * 
     * @Title: selectUserByMap
     * @Description: 多條件組合查詢使用者
     * @param userId
     * @return
     * @throws Exception
     */
	TStudent selectUserByMap(Map<String, Object> parameterMap) throws Exception;
}

package com.zzg.springboot.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

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

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zzg.springboot.entity.TStudent;
import com.zzg.springboot.mapper.TStudentMapper;
import com.zzg.springboot.service.TStudentService;

/**
 * <p>
 * 學員表 服務實現類
 * </p>
 *
 * @author zzg123
 * @since 2018-07-15
 */
@Service
public class TStudentServiceImpl extends ServiceImpl<TStudentMapper, TStudent> implements TStudentService {
	/**
     * 使用者資料訪問介面
     */
	@Resource
    private TStudentMapper tstudentMapper;
	@Override
	public TStudent selectUserByMap(Map<String, Object> parameterMap) throws Exception {
		// TODO Auto-generated method stub
		return tstudentMapper.selectUserByMap(parameterMap);
	}

}

package com.zzg.springboot.controller;


import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzg.springboot.entity.TStudent;
import com.zzg.springboot.service.TStudentService;

/**
 * <p>
 * 學員表 前端控制器
 * </p>
 *
 * @author zzg123
 * @since 2018-07-15
 */
@Controller
@RequestMapping("/tStudent")
public class TStudentController {
	@Resource
	private TStudentService service;

	@RequestMapping("/get")
	@ResponseBody
	public TStudent get(HttpServletRequest request, Model model) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sid", 1);
		TStudent student = this.service.selectUserByMap(map);
		return student;
	}

}

建庫指令碼:

CREATE TABLE `t_student` (
	`sid` INT(11) NOT NULL AUTO_INCREMENT,
	`sname` VARCHAR(255) NULL DEFAULT '0',
	`sex` CHAR(2) NULL DEFAULT '0',
	PRIMARY KEY (`sid`)
)
COMMENT='學員表'
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
MyBatisPlus官網學習地址:http://mp.baomidou.com/#/install