MP实战系列(七)之集成springboot

springboot是现在比较流行的微服使用的框架,springboot本质上就是将spring+springmvc+mybatis零配置化,基本上springboot的默认配置符合我们的开发。当然有一部分还是需要自定义的。

本章不是专门讲springboot的,主要将springboot+mybatis plus是如何整合的。

一、导入pom依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <repositories>
        <!--阿里云仓库-->
        <repository>
            <id>aliyun</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
        <!--快照版本使用,正式版本无需添加此仓库-->
        <repository>
            <id>snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <mybatis-plus-boot-starter.version>2.1.9</mybatis-plus-boot-starter.version>
        <mybatisplus.version>2.1.8</mybatisplus.version>
        <HikariCP.version>2.4.13</HikariCP.version>
        <fastjson.version>1.2.39</fastjson.version>
        <druid.version>1.1.0</druid.version>
    </properties>

    <dependencies>

        <!-- slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.19</version>
        </dependency>

            <!-- Druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

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

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP-java7</artifactId>
            <version>${HikariCP.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <!-- mybatis-plus begin -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>tomcat-jdbc</artifactId>
                    <groupId>org.apache.tomcat</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- mybatis-plus end -->

        <!-- JUnit test dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>2.9.0</version>
            <scope>test</scope>
        </dependency>

        <!-- Code generator test sample-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

    </dependencies>

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

二、编写application.yml配置文件

#app
server:
    port: 8080

#spring
spring:
  devtools:
    restart:
      enabled: false

  datasource:
    url: jdbc:mysql://127.0.0.1:3306/blog?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: 1234
    db-name: blog
    filters: log4j,wall,mergeStat1

#mybatis
mybatis-plus:
  mapper-locations: classpath:/mapper/*Dao.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.blog.springboot.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 2
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true

    #逻辑删除配置(下面3个配置)
    logic-delete-value: 0
    logic-not-delete-value: 1
    #自定义sql注入器,不在推荐使用此方式进行配置,请使用自定义bean注入
    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
    #自定义填充策略接口实现,不在推荐使用此方式进行配置,请使用自定义bean注入
    meta-object-handler: com.blog.springboot.MyMetaObjectHandler
    #自定义SQL注入器
    #sql-injector: com.baomidou.springboot.xxx
    # SQL 解析缓存,开启后多租户 @SqlParser 注解生效
    sql-parser-cache: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
#logging
logging:
  level: warn

三、准备相关的类(例如springboot启动类等)

Application.java

package com.blog.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@SpringBootApplication
public class Application {

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

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
        logger.info("Application is success!");

    }

}

MyMetaObjectHandler.java

package com.blog.springboot;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  注入公共字段自动填充,任选注入方式即可
 */
//@Component
public class MyMetaObjectHandler extends MetaObjectHandler {

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

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("新增");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("更新");
    }
}

MybatisPlusConfig.java

package com.blog.springboot.config;

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

import com.baomidou.mybatisplus.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.mapper.ISqlInjector;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;

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

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.plugins.parser.ISqlParser;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
import com.blog.springboot.MyMetaObjectHandler;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

@Configuration
@MapperScan("com.blog.springboot.mapper*")
public class MybatisPlusConfig {

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MyMetaObjectHandler();
    }

    /**
     * 注入主键生成器
     */
    @Bean
    public IKeyGenerator keyGenerator(){
        return new H2KeyGenerator();
    }

    /**
     * 注入sql注入器
     */
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }

}

  

WebConfig.java

package com.blog.springboot.config;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

/**
 * <p>
 * WEB 初始化相关配置
 * </p>
 */
@ControllerAdvice
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        ObjectMapper objectMapper = builder.build();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);// 忽略 transient 修饰的属性
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
        super.configureMessageConverters(converters);
    }
}

上述类启动类和对mapper文件扫描的类是一定要用到的,功能的话,就不用多说了,启动类,运行即可通过地址栏进入界面,因为我在pom文件中配置了tomcat,就算不配置,springboot也会自带一个servlet容器,扫描类,主要针对xml文件,相当于mybatis的动态扫描的接口编程方式。

四、使用代码生成器进行代码生成(具体可以参考我的MP实战系列(六)之代码生成器讲解)

生成的代码,我还是先贴出来

(1)实体类

package com.blog.springboot.entity;

import java.io.Serializable;

import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;

/**
 * <p>
 *
 * </p>
 *
 * @author yc
 * @since 2018-05-19
 */
@TableName("user")
public class UserEntity extends Model<UserEntity> {

    /**
     * 用户ID
     */
    @TableId(value = "user_id", type = IdType.AUTO)
    private Integer user_id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 性别
     */
    private Integer sex;
    /**
     * 电话
     */
    private String phone;
    /**
     * 密码
     */
    private String password;
    /**
     * 等级
     */
    private Integer level;
    /**
     * 用户创建时间
     */
    @TableField("create_time")
    private String createTime;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 登录标识
     */
    private Integer logo;
    /**
     * 登录时间
     */
    @TableField("login_time")
    private String loginTime;

    public Integer getUserId() {
        return user_id;
    }

    public void setUserId(Integer user_id) {
        this.user_id = user_id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getLogo() {
        return logo;
    }

    public void setLogo(Integer logo) {
        this.logo = logo;
    }

    public String getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(String loginTime) {
        this.loginTime = loginTime;
    }

    @Override
    public String toString() {
        return "User{" +
        "userId=" + user_id +
        ", username=" + username +
        ", sex=" + sex +
        ", phone=" + phone +
        ", password=" + password +
        ", level=" + level +
        ", createTime=" + createTime +
        ", email=" + email +
        ", logo=" + logo +
        ", loginTime=" + loginTime +
        "}";
    }

    @Override
    protected Serializable pkVal() {
        // TODO Auto-generated method stub
        return this.user_id;
    }
}

(2)dao

package com.blog.springboot.mapper;

import com.blog.springboot.entity.UserEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author yc
 * @since 2018-05-19
 */
public interface UserDao extends BaseMapper<UserEntity> {

}

(3)service

package com.blog.springboot.service;

import com.blog.springboot.entity.UserEntity;
import com.baomidou.mybatisplus.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author yc
 * @since 2018-05-19
 */
public interface UserService extends IService<UserEntity> {

}

(4)service实现类

package com.blog.springboot.service.impl;

import com.blog.springboot.entity.UserEntity;
import com.blog.springboot.mapper.UserDao;
import com.blog.springboot.service.UserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yc
 * @since 2018-05-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

}

(5)controller

package com.blog.springboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yc
 * @since 2018-05-19
 */
@Controller
@RequestMapping("/user")
public class UserController {

}

(6)UserDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blog.springboot.mapper.UserDao">

    <!-- 通用查询映射结果 -->
     <resultMap id="BaseResultMap" type="com.blog.springboot.entity.UserEntity">
        <id column="user_id" property="user_id" />
        <result column="username" property="username" />
        <result column="sex" property="sex" />
        <result column="phone" property="phone" />
        <result column="password" property="password" />
        <result column="level" property="level" />
        <result column="create_time" property="createTime" />
        <result column="email" property="email" />
        <result column="logo" property="logo" />
        <result column="login_time" property="loginTime" />
    </resultMap>

<!--     通用查询结果列 -->
    <sql id="Base_Column_List">
        user_id AS userId, username, sex, phone, password, level, create_time AS createTime, email, logo, login_time AS loginTime
    </sql>

</mapper>

(7)springboot单元测试

package com..test;

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.SpringJUnit4ClassRunner;

import com.blog.springboot.Application;
import com.blog.springboot.entity.UserEntity;
import com.blog.springboot.mapper.UserDao;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class UserTest{
    @Autowired
    private UserDao ud;

    @Test
    public void test001() {

        UserEntity userEntity = ud.selectById(1);
        System.out.println(userEntity.getCreateTime()+"||"+userEntity.getEmail());
    }

}

原文地址:https://www.cnblogs.com/youcong/p/9061186.html

时间: 2024-11-08 22:36:10

MP实战系列(七)之集成springboot的相关文章

MP实战系列(二)之集成swagger

其实与spring+springmvc+mybatis集成swagger没什么区别,只是之前写的太不好了,所以这次决定详细写. 提到swagger不得不提rest,rest是一种架构风格,里面有对不同的资源有不同的请求标识.例如PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH等. 对于技术的初学,最好的话还是建议去官网,官网最详细也最权威,虽然不少博客对此有挺好的解说,但还是强烈建议去官网,不要求仔仔细细阅读,至少读个大概. 对于目前,有人要问我swagger能做什么

MP实战系列(九)之集成Shiro

下面示例是在之前的基础上进行的,大家如果有什么不明白的可以参考MP实战系列的前八章 当然,同时也可以参考MyBatis Plus官方教程 建议如果参考如下教程,使用的技术为spring+mybatis plus + springmvc+jdk8+maven工程 满足这个条件可以减少不必要的麻烦,当然持久层也可以用mybatis. 只要按照如下示例来,也不会有大问题的.之前我也强调过mybatis和mybatis plus的区别主要是封装和继承,mybatis plus封装一系列增删改查的方法,但

MP实战系列(十二)之封装方法详解(续二)

继续MP实战系列(十一)之封装方法详解(续一)这篇文章之后. 此次要讲的是关于查询. 查询是用的比较多的,查询很重要,好的查询,加上索引如鱼得水,不好的查询加再多索引也是无济于事. 1.selectById()方法 演示示例: UserEntity user = ud.selectById(33); System.out.println(user.getEmail()); 简单的说明: 如果是在MyBatis中,需要再对应的xml编写这样的sql select column1,column2..

MP实战系列(三)之实体类讲解

首先说一句,mybatis plus实在太好用了! mybaits plus的实体类: 以我博客的用户类作为讲解 package com.blog.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableLogic; imp

MP实战系列(四)之DAO讲解

说到DAO不得不提一个开发名词"三层架构",所谓的三层架构是什么呢?简单的可以概括为数据访问层,业务逻辑层,界面层(又称表现层). 这也是我们Java开发常用的手段,经常有人将三层架构和mvc模式混淆,在我看来,三层架构就是三层架构,mvc只是三层架构中的表现层中的架构,相当于在一个比较大的层面,往里面在细分,mvc细分,可分为模型,视图,控制器,在这里模型通常指数据,也可以叫JavaBean,而视图的话,这个视图就是展示给用户看的,通常用于视图的模板可以为jsp,freemarker

MP实战系列(十三)之批量修改操作(前后台异步交互)

MyBatis的批量操作其实同MyBatis基本是一样的.并无多大区别,要说区别,除了封装的方法之外,主要就是注解方面的区别,比如@TableId.@TableField.@TableName等等区别. 示例描述: 本次描述的是批量相关的操作,主要是批量修改等操作. 项目讲解:如何批量修改开锁方式? 准备环境和IDE工具:MySQL5.7+Maven3以上+JDK8或者JDK7+SSM框架+tomcat8或者tomcat7应用服务器+Eclipse. 本文核心:主要是Controller代码和数

MP实战系列(五)之封装方法讲解

mybatis plus封装的方法怎么用?以及它们对应的sql是那些sql?及其什么情况用? 这些需要说下,以下我将会将我常用的说下,不是常用的,可能提以下或者不提. 根据主键查询 UserEntity userEntity = ud.selectById(id); 上述这个没什么好说的 根据实体查询 UserEntity u = new UserEntity(); u.setEmail("[email protected]"); UserEntity u1 = ud.selectOn

Spring Boot实战系列(7)集成Consul配置中心

本篇主要介绍了 Spring Boot 如何与 Consul 进行集成,Consul 只是服务注册的一种实现,还有其它的例如 Zookeeper.Etcd 等,服务注册发现在微服务架构中扮演这一个重要的角色,伴随着服务的大量出现,服务与服务之间的配置管理.运维管理也变的难以维护,通过 Consul 可以解决这些问题,实现服务治理.服务监控. 关于 Consul 的更多知识点不在这里赘述,但是在学习本节之前还是希望您能先了解下,请移步我之前写的 微服务服务注册发现之 Consul 系列 快速导航

Exchange Server2013 系列七:客户端访问服务器高可用性部署实战

杜飞 在前面的文章中我们介绍了客户端访问服务器的高可用性技术,从这篇文章开始,我们就来看一个详细的高可用性部署方案. 首先,看一下我们的服务器列表: 编号 服务名 IP地址 功能 1 HYV01 IP:10.41.3.6 \16  网关:10.41.1.254 宿主机 2 HYV02 IP:10.41.4.6 \16  网关:10.41.1.254 宿主机 3 DF-DC01 IP:10.41.4.210\16 网关:10.41.1.254 DNS:10.41.4.210   10.41.4.2