JAVA ·

SpringBoot 集成 MybatisPlus

项目介绍

最近在学习新的项目框架,SpringBoot,具体模块可查看集成情况。

SpringBoot 项目多模块(Module)的运用以及设计

点击查看 这个SpringBoot项目的模块区分有: panther -- 父项 panther-common -- 通用包 panther-system -- 系统管理模块 -------···

Mybatis Plus 是什么?

Mybatis-Plus(以下简写MP)是国产开源的一款优秀的持久层框架,团队很积极,版本发布也很稳定,能够节省大量开发时间。

具体可查看官方地址: http://mp.baomidou.com/#/

官方也有自己的集成项目,码云地址:https://gitee.com/baomidou/mybatisplus-spring-boot

这里我们直接跳过集成Mybatis,直接使用Mybatis Plus。

一:在pom.xml中加入依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- mySql 数据库 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- mybatis plus 插件 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>2.3</version>
    <exclusions>
        <exclusion>
            <artifactId>tomcat-jdbc</artifactId>
            <groupId>org.apache.tomcat</groupId>
        </exclusion>
    </exclusions>
</dependency>

二:核心配置文件 MybatisPlusConfig.java

注意:MapperScan,@MapperScan("com.zhuang.*.dao*")记住这个一定要改成你的mapper类包地址
package com.zhuang.db.config;

import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Created with Intellij IDEA
 * @Author : payne
 * @Date : 2018/5/16 - 11:58
 * @Copyright (C), 2018-2018
 * @Descripition : MybatisPlus 配置
 */

@Configuration
@MapperScan("com.zhuang.*.dao*")
public class MybatisPlusConfig {

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}

三:在 applicatom.yml 中加入配置文件

# 运行端口
server:
  port: 820

# 开发环境
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/panther_dev?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root

###################  mybatis-plus配置  ###################
mybatis-plus:
  # 如果是放在src/main/java目录下 classpath:/com/yourPackage/*/mapper/*Mapper.xml
  # 如果是放在resource目录 classpath:/mapper/*Mapper.xml
  mapper-locations: classpath*:/com/zhuang/*/mapper/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.zhuang.*.model
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: false
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #逻辑删除配置(下面3个配置)
    logic-delete-value: 0
    logic-not-delete-value: 1
    # SQL 解析缓存,开启后多租户 @SqlParser 注解生效
    sql-parser-cache: true
  configuration:
    map-underscore-to-camel-case: true
    #配置的缓存的全局开关
    cache-enabled: false

四:创建测试代码

自行创建Controller,Service,impl,model,mapper等文件

代码示例:UserController.java

package com.zhuang.system.controller;

import com.zhuang.system.model.User;
import com.zhuang.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Created with Intellij IDEA
 * @Author : payne
 * @Date : 2018/5/14 - 10:25
 * @Copyright (C), 2014-2018
 * @Descripition : User Controller 控制层
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/index")
    public String hello() {
        List<User> userList = userService.getAllUser();
        if (userList.size() > 0) {
            return "SUCCESS";
        }
        return "ERROR";
    }
}

代码示例:UserMapper.java

package com.zhuang.system.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.zhuang.system.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Created with Intellij IDEA
 * @Author : payne
 * @Date : 2018/5/14 - 10:26
 * @Copyright (C), 2014-2018
 * @Descripition : User 表数据库控制层接口
 */
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {

}

代码示例:UserServiceImpl.java

package com.zhuang.system.service.impl;

import com.zhuang.system.dao.UserMapper;
import com.zhuang.system.model.User;
import com.zhuang.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Created with Intellij IDEA
 * @Author : payne
 * @Date : 2018/5/14 - 10:26
 * @Copyright (C), 2014-2018
 * @Descripition : User Service 实现类
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUser() {
        // 获取MP里面的通用方法,查询所有表数据,return 回 List
        List<User> userList = userMapper.selectList(null);
        for (User u : userList) {
            System.out.println(u.getId() + " - " + u.getUserName());
            System.out.println(" =============== Mybatis Plus ================ ");
            // 根据MP通用方法,根据ID来进行单独查询
            User user = userMapper.selectById(u.getId());
            System.out.println(user.getId() + " - " + user.getUserName());
        }
        return userList;
    }
}

代码示例:PantherWebApplication.java

注意:记住修改 @MapperScan("com.zhuang.*.dao*")
package com.zhuang;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
//启注解事务管理
@EnableTransactionManagement
@MapperScan("com.zhuang.*.dao*")
public class PantherWebApplication {

    protected static final Logger logger = LoggerFactory.getLogger(PantherWebApplication.class);

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

        logger.info("SpringBoot WebApplication Start Success . ");
    }
}

五:访问

访问我们的项目:http://localhost:820/user/index

访问后的结果以及控制台的输出。

整体的项目集成是基于文章开头所说的项目介绍里面的项目。

参与评论