SpringBoot2.1.0整合mybatis plus3.0

先进入springBoot自动构建工程的网址[https://start.spring.io/]
在这里插入图片描述加入常用依赖后会自动生成maven工程下载后导入IDE即可我把完整的pom文件贴出来

<?xml version="1.0" encoding="UTF-8"?>
<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>

	<groupId>com.example.kk</groupId>
	<artifactId>Spring-Boot-MyBatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Spring-Boot-MyBatis</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
	<!-- jdbc驱动 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>
		
		
	<!-- lombok -->
	<dependency>
		   <groupId>org.projectlombok</groupId>
		   <artifactId>lombok</artifactId>
		   <version>1.18.4</version>
		   <scope>provided</scope>
	</dependency>

    	<!-- mybatis-plus 3.0.5-->
    	<dependency>
	        <groupId>com.baomidou</groupId>
	        <artifactId>mybatis-plus-boot-starter</artifactId>
	        <version>3.0.5</version>
    	</dependency>
    	
    	<!-- guava -->
	<dependency>
		 <groupId>com.google.guava</groupId>
		 <artifactId>guava</artifactId>
		<version>27.0-jre</version>
	</dependency>
		
		<!-- 分页插件 -->
        <dependency>
		   <groupId>com.github.pagehelper</groupId>
		   <artifactId>pagehelper-spring-boot-starter</artifactId>
		   <version>1.2.5</version>
	</dependency>
		
		
	<!-- freemarker -->
	<dependency>
		   <groupId>org.freemarker</groupId>
		   <artifactId>freemarker</artifactId>
		   <version>2.3.28</version>
	</dependency>
		
		
	<!-- apache模板引擎 -->
	<dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>


    	
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

其实这一步就整合成功了,接下在根据mybatis-plus官网步骤往下走就行了怎么也得写个hello world把0.0
我把mybatis-plus的代码生成器测试了下,先看代码生成器

package com.example.kk.generator;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
 * 
 * @author kk
 * AutoGenerator MyBatis-Plus 代码生成器
 */
public class CodeGenerator {

	
   /**
    * <p>
    * 读取控制台内容
    * </p>
    */
   public static String scanner(String tip) {
       Scanner scanner = new Scanner(System.in);
       StringBuilder help = new StringBuilder();
       help.append("请输入" + tip + ":");
       System.out.println(help.toString());
       if (scanner.hasNext()) {
           String ipt = scanner.next();
           if (StringUtils.isNotEmpty(ipt)) {
               return ipt;
           }
       }
       throw new MybatisPlusException("请输入正确的" + tip + "!");
   }
   
   
   public static void main(String[] args) {
       // 代码生成器
       AutoGenerator mpg = new AutoGenerator();

       // 全局配置
       GlobalConfig gc = new GlobalConfig();
       String projectPath = System.getProperty("user.dir");
       //生成文件输出目录
       gc.setOutputDir(projectPath + "/src/main/java");
       //开发人员
       gc.setAuthor("kk");
       //是否打开输出目录
       gc.setOpen(true);
       //service命名方式
       gc.setServiceName("%sService");
       //service impl命名方式
       gc.setServiceImplName("%sServiceImpl");
       //自定义文件命名,注意 %s 会自动填充表实体属性!
	   gc.setMapperName("%sMapper");
	   gc.setXmlName("%sMapper");
	   gc.setFileOverride(true);
	   gc.setActiveRecord(true);
	   gc.setEnableCache(false);// XML 二级缓存
	   gc.setBaseResultMap(true);// XML ResultMap
	   gc.setBaseColumnList(false);// XML columList
       mpg.setGlobalConfig(gc);

       // 数据源配置
       DataSourceConfig dsc = new DataSourceConfig();
       dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC");
       dsc.setDriverName("com.mysql.cj.jdbc.Driver");
       dsc.setUsername("root");
       dsc.setPassword("fx8350");
       mpg.setDataSource(dsc);

       // 包配置
       PackageConfig pc = new PackageConfig();
       //父包模块名
       //pc.setModuleName(scanner("kk"));
       //父包名。// 自定义包路径  如果为空,将下面子包名必须写全部, 否则就只需写子包名
       pc.setParent("com.kk.admin");
       pc.setEntity("pojo");
       pc.setService("service");
       pc.setServiceImpl("service.impl");
       //设置控制器包名
       pc.setController("controller");
       mpg.setPackageInfo(pc);
       
       /**
       // 自定义配置
       InjectionConfig cfg = new InjectionConfig() {
           @Override
           public void initMap() {
               // to do nothing
           }
       };
       List<FileOutConfig> focList = new ArrayList<>();
       focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {

		@Override
		public String outputFile(TableInfo arg0) {
			// 自定义输入文件名称
            return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                    + "/" + arg0.getEntityName() + "Mapper" + StringPool.DOT_XML;
		}
       });
       
       cfg.setFileOutConfigList(focList);
       mpg.setCfg(cfg);
        **/
       mpg.setTemplate(new TemplateConfig().setXml(null));
       
       // 策略配置
       StrategyConfig strategy = new StrategyConfig();
       //数据库表映射到实体的命名策略
       strategy.setNaming(NamingStrategy.underline_to_camel);
       //数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
       strategy.setColumnNaming(NamingStrategy.underline_to_camel);
       //自定义继承的Entity类全称,带包名
       //strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
       //【实体】是否为lombok模型(默认 false)
       strategy.setEntityLombokModel(true);
       //生成 @RestController 控制器
       strategy.setRestControllerStyle(true);
       //自定义继承的Controller类全称,带包名
       //strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
       //需要包含的表名,允许正则表达式
       //strategy.setInclude(scanner("user"));
       strategy.setInclude("user");
       //自定义基础的Entity类,公共字段
       //strategy.setSuperEntityColumns("id");
       //驼峰转连字符
       strategy.setControllerMappingHyphenStyle(true);
       //表前缀
       strategy.setTablePrefix(pc.getModuleName() + "_");
       mpg.setStrategy(strategy);
       //mpg.setTemplateEngine(new FreemarkerTemplateEngine());
       mpg.execute();
   }
   
}

在这里插入图片描述
以上就是生成的代码,接下测试一下看看成功整合了吗
创建表

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL COMMENT '主键ID',
  `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


添加数据

INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('1', 'Jone', '18', 'test1@baomidou.com');
INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('2', 'Jack', '20', 'test2@baomidou.com');
INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('3', 'Tom', '28', 'test3@baomidou.com');
INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('4', 'Sandy', '21', 'test4@baomidou.com');
INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('5', 'Billie', '24', 'test5@baomidou.com');
INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('1059335521349685249', '小萝莉', '18', 'xiaoluoli@qq.com');
INSERT INTO `mybatisplus`.`user` (`id`, `name`, `age`, `email`) VALUES ('1059335521538428930', '花花', '2', 'huahua@qq.com');

然后配置下数据库连接

server:
  port: 8081

# DataSource Config
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: xxxxxx
    

在这里插入图片描述代码结构如上

package com.example.kk.config;

import java.util.Properties;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.github.pagehelper.PageHelper;

/**
 * 
 * @author kk
 * MybatisPlus配置类
 */
//@EnableTransactionManagement
@Configuration
@MapperScan("com.example.kk.mapper")
public class MybatisPlusConfig {

	
	/**
	 * 分页
	 * @return
	 */
	@Bean
	public PaginationInterceptor paginationInterceptor(){
		return new PaginationInterceptor();
	}
   	
	
	/**
     * SQL执行效率插件
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
}

mapper接口

package com.example.kk.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.kk.entity.User;

public interface UserMapper extends BaseMapper<User>  {

}

package com.example.kk.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.kk.entity.User;
import com.example.kk.service.UserServiceImpl;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;

/**
 * 
 * @author kk
 *
 */
@RestController
public class HelloController {

	@RequestMapping("/")
	public String index(){
		return "Hello String Boot!";
	}
	
	
	
	@Autowired
	UserServiceImpl userService;
	
	@GetMapping("/select_map")
	public Object selectMapTest(){
		return userService.mybatuisPlusTest();
	}
	
	
	/**
	 * 批量保存
	 * @return
	 */
	@GetMapping("/save_batch")
	public Boolean saveOrUpdateBatchTest(){
		List<User> userList = Lists.newArrayList(
				new User(null, "小萝莉", 18, "xiaoluoli@qq.com"),
				new User(null, "花花", 2, "huahua@qq.com")
				);
		//使用创建者模式设值实体类
		User u1 = User.builder().name("小萝莉").age(18).email("xiaoluoli@qq.com").build();
		return  userService.saveOrUpdateBatch(userList);
	}
	
	
	/*
	 * 测试分页
	 */
	@GetMapping("/page")
	public Object testPage(){
		PageInfo<User> pageList = userService.pageList();
		return pageList;
	}
	
	
}

实体类

package com.example.kk.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;

@RequiredArgsConstructor
//@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Data
@Builder
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

service层

 package com.example.kk.service.Impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.kk.entity.User;

public interface UserService extends IService<User>{

}

实现层

package com.example.kk.service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.kk.entity.User;
import com.example.kk.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;

//强制使用cgbin
//@EnableAspectJAutoProxy(proxyTargetClass = true )
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  {

	
	@Autowired
	UserMapper userMapper;
	
	
	public List<Map<String, Object>> mybatuisPlusTest(){
		return  userMapper.selectMaps(null);
	}
	
	
	/**
	 * 测试分页
	 * @return
	 */
	public PageInfo<User> pageList(){
		PageHelper.startPage(1, 2);
		List<User> selectList = userMapper.selectList(new QueryWrapper<User>());
		PageInfo<User> pageInfo = new PageInfo<User>(selectList);
		return pageInfo;
	}
	
	
	
	@Override
	public boolean saveOrUpdateBatch(Collection<User> entityList) {
		return super.saveOrUpdateBatch(entityList);
	}


	
	
	
}

单元测试

package com.example.kk.test;

import java.util.List;
import java.util.Map;

import org.junit.Assert;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.kk.entity.User;
import com.example.kk.mapper.UserMapper;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest extends ServiceImpl<UserMapper, User> {

	@Autowired
	UserMapper userMapper;
	
	
	@Test
	public void testSelect(){
		System.out.println("----- selectAll method test ------");
		List<User> selectList = userMapper.selectList(null);
		Assert.assertEquals(5, selectList.size());
		selectList.forEach(System.out::println);
	}
	
	
	@Test
	public void mybatuisPlusTest(){
		//返回map
		List<Map<String, Object>> selectMaps = userMapper.selectMaps(null);
		selectMaps.forEach(System.out::println);
		
	}
	
	
	@Test
	public void mybatisModel(){
	}
}

springBoot启动类

package com.example.kk;

import java.sql.Date;
import java.util.Arrays;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

//exclude=DataSourceAutoConfiguration.class
@SpringBootApplication
@MapperScan("com.example.kk.mapper")
public class SpringBootMyBatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootMyBatisApplication.class, args);
	}
	
	@Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
        	
           System.out.println("Let's inspect the beans provided by Spring Boot:");

           String[] beanNames = ctx.getBeanDefinitionNames();
           Arrays.sort(beanNames);
           for (String beanName : args) {
			 System.out.println(beanName);
		}

        };
    }
}

展开阅读全文

没有更多推荐了,返回首页