Spring Boot项目整合Mybatis-Plus详解

前言:
1.该项目展示的在spring boot中创建mybatis-plus
2.在创建好spring boot项目结构下进行 (传送门
3.项目中不要忘记各个模块之间的依赖导入

一. 项目结构
1.jpeg
说明:1. 这是项目的整个结构
     2. controller :控制器类, 可自动生成也可自己写
     3. config :配置类文件
     4. generator :代码自动成器
     5. entity、mapper、service :自动生成
     6. extService :自己封装的服务层
二. 自动生成代码(传送门
说明:1.生成后的package放到对应的模块下面(这里是第二个红框内)
三. 配置数据库文件datasource-dev.properties

1.需导入的pom依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>2.0.7</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.14</version>
</dependency>

2.datasource-dev.properties文件内容

#虽然是灰的,但是已经引用了

# mysql配置

spring.datasource.url=jdbc:mysql://192.168.0.3:8888/test?useUnicode=false&autoReconnect=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# mybatis_config配置
# mybatis.mapper-locations 的路径是Mapper.xml文建所在路径
# mybatis.typeAliasesPackage 的包为entity所在类

mybatis.mapper-locations=classpath:com/mybatis/repository/mapper/impl/*Mapper.xml
mybatis.typeAliasesPackage=com.mybatis.repository.entity

说明:1. pom依赖不需要重复引入
     2. mysql配置一定要换成自己的数据库信息
     3. mybatis_config配置中一定要注意路径一定要修改
     4. datasource-dev.properties是开发环境的数据库,
        datasource-pro.properties是线上环境的数据库
四. config包的引入

1.结构

2.jpeg

2.config里面的类是对spring bean的注入

//配置错误或是没有配置改包的类,编译会报以下错误

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xxxXXX': 
Unsatisfied dependency expressed through field 'xxxXXX'; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'personServiceImpl': Unsatisfied dependency expressed through field 'baseMapper';
 nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'com.mybatis.repository.mapper. XXX Mapper' available: 
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: 
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

3.config包的配置代码
(1)DatasourceProperties.java(不需要动)

package com.mybatis.repository.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;

@Configuration
public class DatasourceProperties {

    @Configuration
    @Profile("dev")
    @PropertySource("classpath:datasource-dev.properties")
    static class Dev {
    }
    
    @Configuration
    @Profile("pre")
    @PropertySource("classpath:datasource-pre.properties")
    static class Pre {
    }
    
    @Configuration
    @Profile("pro")
    @PropertySource("classpath:datasource-pro.properties")
    static class Product {
    }
}

(2)InitConfig.java

package com.mybatis.repository.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

// @MapperScan所扫描的要换成自己需要的mapper
@MapperScan("com.mybatis.repository.mapper*")
@Configuration
public class InitConfig {

}

(3)MybatisPlusConfig.java(不需要动)

package com.mybatis.repository.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

@Configuration
@AutoConfigureAfter(DatasourceProperties.class)
@EnableConfigurationProperties(MybatisProperties.class)
public class MybatisPlusConfig {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private MybatisProperties properties;

    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    @Autowired(required = false)
    private Interceptor[] interceptors;

    @Autowired(required = false)
    private DatabaseIdProvider databaseIdProvider;

    /**
     * mybatis-plus分页插件
     *
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

    /**
     * 这里全部使用mybatis-autoconfigure 已经自动加载的资源,不手动指定
     *
     * 配置文件和mybatis-boot的配置文件同步
     */
    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(dataSource);
        mybatisPlus.setVfs(SpringBootVFS.class);
        if (StringUtils.hasText(this.properties.getConfigLocation())) {
            mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        }
        mybatisPlus.setConfiguration(properties.getConfiguration());
        if (!ObjectUtils.isEmpty(this.interceptors)) {
            mybatisPlus.setPlugins(this.interceptors);
        }
        // MP 全局配置,更多内容进入类看注释

        GlobalConfiguration globalConfig = new GlobalConfiguration();
        globalConfig.setDbType(DBType.MYSQL.name());//数据库类型

        // ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
        globalConfig.setIdType(2);

        //MP 属性下划线 转 驼峰 , 如果原生配置 mc.setMapUnderscoreToCamelCase(true) 开启,该配置可以无。
        //globalConfig.setDbColumnUnderline(true);

        mybatisPlus.setGlobalConfig(globalConfig);
        MybatisConfiguration mc = new MybatisConfiguration();

        // 对于完全自定义的mapper需要加此项配置,才能实现下划线转驼峰
        //mc.setMapUnderscoreToCamelCase(true);

        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        mybatisPlus.setConfiguration(mc);
        if (this.databaseIdProvider != null) {
            mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
        }
        if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
            mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        }
        if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
            mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
        }
        if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
            mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
        }
        return mybatisPlus;
    }
}

五. 最一步的配置
  1. 结构
3.jpeg
  1. 启动类Application.java
package com.mybatis.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.mybatis") // 这个一定要换成自己的包名
public class Application {

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

  1. 数据库选用配置
//  这一步没有配置的话编译会报如下错误
Cannot determine embedded database driver class for database type NONE

方法一:在启动类所在的application.properties所在的文件添加
spring.profiles.active=devspring.profiles.active=pro
方法二:在编译处修改

第一步:


4.jpeg

第二步:


WechatIMG32.jpeg
说明:到了这一步所有配置都已经完成了,编译理论上是不会报错的
     接下来就是controller,和自己封装的service的编写,直接给出代码demo
六. controller和service的demo
  1. PersonController.java
package com.mybatis.api.controller;

import com.mybatis.repository.entity.Person;
import com.mybatis.service.extService.PersonExtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author SamGroves
 * @since 2017-09-22
 */
@Controller
@RequestMapping("/api")
public class PersonController {

    @Autowired
    PersonExtService personExtService;

    /**
     * 查
     */
    @RequestMapping(value = "/test")
    @ResponseBody
    public Person test() {
        return personExtService.findPersonById(1);
    }

    /**
     * 删
     */
    @RequestMapping(value = "/test4")
    @ResponseBody
    public void test4() {
        personExtService.delectPersonById(2);
    }
}

  1. PersonExtService.java
package com.mybatis.service.extService;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mybatis.repository.entity.Person;
import com.mybatis.repository.mapper.PersonMapper;
import com.mybatis.repository.service.IPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author: SamGroves
 *
 * Description: 要继承于ServiceImpl<EntityMapper, Entity>
 *              在类上要添加注解 @Service
 *
 * Date: 2017/9/22
 */
@Service
public class PersonExtService extends ServiceImpl<PersonMapper, Person>{

    @Autowired
    private IPersonService personService;

    /**
     * 通过ID查找
     */
    public Person findPersonById(Integer id) {
        return  personService.selectById(id);
    }

    /**
     * 新增信息
     */
    public void addPerson(String name, String sex, String code, Integer age) {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        person.setSex(sex);
        person.setCode(code);
        person.insert();
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容