SpringBoot攻略七、集成mybatisplus实战

在【SpringBoot攻略六】基础上做如下修改:

pom.xml
我们删除mybatis-spring-boot-starter和pagehelper-spring-boot-starter依赖。
新增依赖:

<!-- mybatis plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

application.properties
去掉mybatis和pagehelper的配置项
新增配置项:

#mybatis plus
mybatis-plus.configLocation=classpath:mybatis/mybatis-config.xml
mybatis-plus.mapperLocations=classpath*:/mybatis/**/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.javasgj.springboot.mybatisplus.domain
mybatis-plus.typeAliasesSuperType=com.javasgj.springboot.mybatisplus.domain.BaseEntity

mybatis-config.xml
新增分页插件:

<plugins>  
    <!-- mybatisplus分页拦截器 -->
    <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
    </plugin>  
</plugins> 

好了,开始实战

mybatisplus开发指南:https://mp.baomidou.com/

1、创建实体类
Pagination:

package com.javasgj.springboot.mybatisplus.domain;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;

/**
 * 分页工具类
 */
public class Pagination {

    /**
     * 当前页码
     */
    @TableField(exist = false)
    @JSONField(serialize = false)
    protected int pageIndex;
    
    /**
     * 每页大小
     */
    @TableField(exist = false)
    @JSONField(serialize = false)
    protected int pageSize;
    
    
    public int getPageIndex() {
        return pageIndex;
    }
    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}

BaseEntity:

package com.javasgj.springboot.mybatisplus.domain;

import java.util.Date;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

/**
 * 基础实体类
 */
public class BaseEntity extends Pagination {

    // 主键
    @TableId(type=IdType.UUID)
    protected String id;
    
    // 创建人
    protected String cjrId;
    protected String cjr;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    protected Date cjSj;
    
    // 更新人
    protected String gxrId;
    protected String gxr;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    protected Date gxSj;
    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getCjrId() {
        return cjrId;
    }
    public void setCjrId(String cjrId) {
        this.cjrId = cjrId;
    }
    public String getCjr() {
        return cjr;
    }
    public void setCjr(String cjr) {
        this.cjr = cjr;
    }
    public Date getCjSj() {
        return cjSj;
    }
    public void setCjSj(Date cjSj) {
        this.cjSj = cjSj;
    }
    public String getGxrId() {
        return gxrId;
    }
    public void setGxrId(String gxrId) {
        this.gxrId = gxrId;
    }
    public String getGxr() {
        return gxr;
    }
    public void setGxr(String gxr) {
        this.gxr = gxr;
    }
    public Date getGxSj() {
        return gxSj;
    }
    public void setGxSj(Date gxSj) {
        this.gxSj = gxSj;
    }
}

Commonfile:

package com.javasgj.springboot.mybatisplus.domain;

import com.baomidou.mybatisplus.annotation.TableName;

@TableName("t_c_file")
public class Commonfile extends BaseEntity {
    
    // 以下为实体类对应表的所有字段
    private String name;
    private Long size;
    private String path;
    private String type;
    private String ywId;
    
    // 额外辅助字段
    
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getSize() {
        return size;
    }
    public void setSize(Long size) {
        this.size = size;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getYwId() {
        return ywId;
    }
    public void setYwId(String ywId) {
        this.ywId = ywId;
    }
}

2、创建mapper
CommonfileMapper:

package com.javasgj.springboot.mybatisplus.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.javasgj.springboot.mybatisplus.domain.Commonfile;

public interface CommonfileMapper extends BaseMapper<Commonfile> {
    
    public void updateAllColumnById(Commonfile commonfile);
}

src/main/resources创建xml配置sql
mybatis/common/CommonfilePlusMapper.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.javasgj.springboot.mybatisplus.dao.CommonfileMapper">
    
    <update id="updateAllColumnById" parameterType="Commonfile">
        update t_c_file
        <trim prefix="set" suffixOverrides=",">
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="name == null or name == ''">
                name = null,
            </if>
            <if test="size != null and size != ''">
                size = #{size},
            </if>
            <if test="size == null or size == ''">
                size = null,
            </if>
            <if test="path != null and path != ''">
                path = #{path},
            </if>
            <if test="path == null or path == ''">
                path = null,
            </if>
            <if test="type != null and type != ''">
                type = #{type},
            </if>
            <if test="type == null or type == ''">
                type = null,
            </if>
            <if test="ywId != null and ywId != ''">
                yw_id = #{ywId},
            </if>
            <if test="ywId == null or ywId == ''">
                yw_id = null,
            </if>
        </trim>
        where id = #{id}
    </update>
</mapper>

3、创建service
CommonfileService:

package com.javasgj.springboot.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.javasgj.springboot.mybatisplus.domain.Commonfile;

public interface CommonfileService extends IService<Commonfile> {

    public void updateAllColumnById(Commonfile commonfile);
}

CommonfileServiceImpl:

package com.javasgj.springboot.mybatisplus.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasgj.springboot.mybatisplus.dao.CommonfileMapper;
import com.javasgj.springboot.mybatisplus.domain.Commonfile;

@Service
public class CommonfileServiceImpl extends ServiceImpl<CommonfileMapper, Commonfile> implements CommonfileService {

    @Override
    @Transactional
    public void updateAllColumnById(Commonfile commonfile) {
        
        this.baseMapper.updateAllColumnById(commonfile);
    }
}

4、创建controller
CommonfileController:

package com.javasgj.springboot.mybatisplus.controller;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javasgj.springboot.mybatisplus.domain.Commonfile;
import com.javasgj.springboot.mybatisplus.service.CommonfileService;
import com.javasgj.springboot.mybatisplus.utils.StringUtil;

/**
 * 公共附件管理模块
 */
@RestController
@RequestMapping("/commonfile")
public class CommonfileController {
    
    @Autowired
    private CommonfileService commonfileService;
    
    @RequestMapping(value="findById", method=RequestMethod.GET)
    public Commonfile findById(String id, HttpServletRequest request, HttpServletResponse response) {
        
        return commonfileService.getById(id);
    }

    @RequestMapping(value="findByPage", method=RequestMethod.POST)
    public IPage<Commonfile> findByPage(@RequestBody Commonfile commonfile, HttpServletRequest request, HttpServletResponse response) {
        
        Page<Commonfile> page = new Page<Commonfile>();
        page.setCurrent(commonfile.getPageIndex());
        page.setSize(commonfile.getPageSize());
        
        QueryWrapper<Commonfile> queryWrapper = new QueryWrapper<Commonfile>();
        if(!StringUtil.isEmpty(commonfile.getName())) {
            queryWrapper.like("name", commonfile.getName());
        }
        return commonfileService.page(page, queryWrapper);
    }
    
    @RequestMapping(value="findAll", method=RequestMethod.POST)
    public List<Commonfile> findAll(@RequestBody Commonfile commonfile, HttpServletRequest request, HttpServletResponse response) {
        
        QueryWrapper<Commonfile> queryWrapper = new QueryWrapper<Commonfile>();
        if(!StringUtil.isEmpty(commonfile.getName())) {
            queryWrapper.like("name", commonfile.getName());
        }
        return commonfileService.list(queryWrapper);
    }

    @RequestMapping(value="save", method=RequestMethod.POST)
    public void save(@RequestBody Commonfile commonfile, HttpServletRequest request, HttpServletResponse response) {
        
        commonfileService.save(commonfile);
    }

    @RequestMapping(value="update", method=RequestMethod.POST)
    public void update(@RequestBody Commonfile commonfile, HttpServletRequest request, HttpServletResponse response) {
        
        commonfileService.updateAllColumnById(commonfile);
    }
    
    @RequestMapping(value="deleteById", method=RequestMethod.POST)
    public void deleteById(@RequestBody Commonfile commonfile, HttpServletRequest request, HttpServletResponse response) {
        
        commonfileService.removeByIds(Arrays.asList(commonfile.getId().split(",")));
    }   
}

5、应用启动类

package com.javasgj.springboot.mybatisplus;

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

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * spring boot应用启动类
 * @MapperScan:mybatis Mapper接口扫描,如果不加此注解,那么必须在Mapper接口上加@Mapper
 */
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.javasgj.springboot.mybatisplus.**.dao")
public class Application {
    
    public static void main(String[] args) {
        
        SpringApplication.run(Application.class, args);
    }
    
    /**
     * fastjson替换默认的jackjson(springmvc)
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue, 
                                            SerializerFeature.WriteNullListAsEmpty);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        // 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(converter);
    }
}

6、测试,使用postman
findById:
get方式:http://127.0.0.1:8080/springboot/commonfile/findById?id=6ff2a63a45da4f27bdd8f292c3b24c27

findByPage:
post方式:http://127.0.0.1:8080/springboot/commonfile/findByPage
Headers头添加:Content-Type:application/json
Body中选择raw:{"pageIndex": "1", "pageSize": "2"}

findAll:
post方式:http://127.0.0.1:8080/springboot/commonfile/findAll
Headers头添加:Content-Type:application/json
Body中选择raw:{"name": "86"}

save:
post方式:http://127.0.0.1:8080/springboot/commonfile/save
Headers头添加:Content-Type:application/json
Body中选择raw:{"name": "86"}

update:
post方式:http://127.0.0.1:8080/springboot/commonfile/update
Headers头添加:Content-Type:application/json
Body中选择raw:{"id":"0e821cf5423a4877899a1649a6de650e", "name": "86111"}

deleteById:
post方式:http://127.0.0.1:8080/springboot/commonfile/deleteById
Headers头添加:Content-Type:application/json
Body中选择raw:{"id":"0e821cf5423a4877899a1649a6de650e,57bb99851d9947208569540d28c1c453"}

OK,整合完了!

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

推荐阅读更多精彩内容

  • 在【SpringBoot攻略二、Hello World实战】基础上追加... 1、pom.xml引入依赖 2、ap...
    红哥讲java阅读 282评论 0 0
  • 对于java中的思考的方向,1必须要看前端的页面,对于前端的页面基本的逻辑,如果能理解最好,不理解也要知道几点。 ...
    神尤鲁道夫阅读 806评论 0 0
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,694评论 0 3
  • =========================================================...
    _灯火阑珊处阅读 2,404评论 0 3
  • “我们一生会遇到许多人,如搭乘一班熙攘的地铁,大量的涌向你,他们与你交汇,与你擦肩,在某一时刻,你甚至与其中一些人...
    淡淡说道阅读 333评论 0 1