springboot 集成mybatisPlus分析

不点 阅读:253 2021-03-31 21:12:23 评论:0

今天整理下自己在整合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


声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号