美文网首页springboot程序员Java学习笔记
Spring Boot项目整合Mybatis-Plus详解

Spring Boot项目整合Mybatis-Plus详解

作者: samgroves | 来源:发表于2017-09-22 17:33 被阅读5048次

前言:
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();
    }
}

相关文章

网友评论

    本文标题:Spring Boot项目整合Mybatis-Plus详解

    本文链接:https://www.haomeiwen.com/subject/aaefextx.html