Mybatisplus 相关操作之 IService BaseMapper ServiceImpl 简单应用

本篇主要介绍mybatisplus的简单应用这里对mybatisplus中配置遇到的问题及extent、implement所导入的包也为大家方便引入依赖1引入相关依赖依赖只是参考,每人的仓库不同,代码块内容仅作参考<dependencies><dependency><groupId>org.springframework.boot</groupId><artifac

大家好,又见面了,我是你们的朋友全栈君。

本篇主要介绍mybatisplus的简单应用

这里对mybatisplus中配置遇到的问题及extent、implement所导入的包也为大家方便引入依赖

1 引入相关依赖

依赖只是参考,每人的仓库不同,代码块内容仅作参考Mybatisplus 相关操作之 IService BaseMapper ServiceImpl 简单应用

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-core</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>

2 yml文件配置

部分小伙伴 mysql-connector-java 版本过高,需要将 driver-class-name换成:com.mysql.cj.jdbc.Driver

server:
  port: 9999

# 配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true
    username: root
    password: 123456

3 相关的数据库表数据

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_area
-- ----------------------------
DROP TABLE IF EXISTS `tb_area`;
CREATE TABLE `tb_area`  (
  `area_id` int(2) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `area_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '区域名称',
  `priority` int(2) NOT NULL DEFAULT 0 COMMENT '优先级',
  `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime NULL DEFAULT NULL COMMENT '最后修改时间',
  PRIMARY KEY (`area_id`) USING BTREE,
  UNIQUE INDEX `UK_AREA`(`area_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

SET FOREIGN_KEY_CHECKS = 1;

代码环节

1 目录结构

Mybatisplus 相关操作之 IService BaseMapper ServiceImpl 简单应用

2 dao数据

import java.io.Serializable;
import java.util.Date;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class BaseEntity<T extends Model> extends Model {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date updateTime;

    @Override
    protected Serializable pkVal() {
        return super.pkVal();
    }

}
import java.io.Serializable;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_area")
public class Book extends BaseEntity<Book> implements Serializable {

    @TableId(value = "area_id", type = IdType.AUTO)
    private Integer areaId;

    private String areaName;

    private int priority;

}

3 service层

需要注意的是import的对象是什么(吃过这里的亏)

import com.alnex.myOwn.dao.Book;
import com.baomidou.mybatisplus.extension.service.IService;

public interface IBookService extends IService<Book> {
}
import org.springframework.stereotype.Service;

import com.alnex.myOwn.dao.Book;
import com.alnex.myOwn.mapper.BookMapper;
import com.alnex.myOwn.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class BookServerImpl extends ServiceImpl<BookMapper, Book> implements IBookService{
}

4 map包下

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface SuperMapper<T> extends BaseMapper<T> {
}
import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.alnex.myOwn.dao.Book;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface BookMapper extends BaseMapper<Book> {

    @Select("SELECT * FROM `tb_area`")
    List<Book> selectList();
}

5 controller包下

import javax.annotation.Resource;
import java.util.List;
import org.springframework.web.bind.annotation.*;

import com.alnex.myOwn.dao.Book;
import com.alnex.myOwn.service.IBookService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/book")
public class IndexController {

    @Resource
    private IBookService bookServer;

    @GetMapping("/list/{pageNum}/{pageSize}")
    public Object index(@PathVariable("pageNum") int pageNum,@PathVariable("pageSize") int pageSize){

        System.out.println("pageNum = " + pageNum);
        System.out.println("pageSize = " + pageSize);

        log.info("----- baseMapper 自带分页 ------");
        Page<Book> pg = new Page<>(pageNum, pageSize);

        IPage<Book> bookIPage = bookServer.page(pg);
        log.info("总条数 ------> [{}]" , bookIPage.getTotal());
        log.info("当前页数 ------> [{}]" , bookIPage.getCurrent());
        log.info("当前每页显示数 ------> [{}]" , bookIPage.getSize());
        log.info("当前页数据 ------> [{}]" , bookIPage.getRecords());

        print(bookIPage.getRecords());

        log.info("----- Book 列表数据展示 ------");
        List<Book> list = bookServer.list();
        log.info("list 数据 ------> {[]} " + list);

        return bookIPage;
    }

    private <T> void print(List<Book> list) {
        if (!CollectionUtils.isEmpty(list)) {
            for (Book t : list) {
                log.info("Book 数据为 ----> [{}]",t);
                log.info("[{}]",t.getCreateTime());
                log.info("[{}]",t.getUpdateTime());
            }
        }
    }

    @GetMapping("/getOne/{areaId}")
    public Object getOne(@PathVariable("areaId") int areaId){

        System.out.println(areaId);

        //方法一
        Book other = bookServer.getById(areaId);
        log.info("book 数据为 ------> [{}]" , other);
        System.out.println();

        //方法二
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("area_id",areaId);

        Book book = bookServer.getOne(queryWrapper);
        log.info("book1 数据为 ------> [{}]" , book);

        return book;
    }

    @PutMapping("/save")
    public Object save(@RequestBody Book book){
        return bookServer.save(book);
    }

    @DeleteMapping("/del/{areaId}")
    public Object del(@PathVariable("areaId") int areaId){

        boolean b;

        //方式一
        // b = bookServer.removeById(areaId);

        //方式二
        QueryWrapper<Book> queryWrapper  =new QueryWrapper<>();
        queryWrapper.eq("area_id",areaId);

        b = bookServer.remove(queryWrapper);

        return b;
    }

    @PutMapping("/update")
    public Object update(@RequestBody Book book){
        return bookServer.updateById(book);
    }

    //批量新增或者修改方法,判断ID是否存在,如果ID不存在执行新增,如果ID存在先执行查询语句,查询结果为空新增,否则修改。
    @PutMapping("/addMore")
    public Object addList(@RequestBody List<Book> list){
        return bookServer.saveOrUpdateBatch(list);
    }
}

6 config包下【重要】

在之前配置config 时只配置mybatisplus 的分页插件,发现在启动时一直报   Property ‘sqlSessionFactory’ or ‘sqlSessionTemplate’ are required 的错误

附查询的相关资料:https://www.cnblogs.com/hawk0035/p/3337283.html?utm_source=tuicool

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.incrementer.DB2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;


@Configuration
@MapperScan("com.alnex.myOwn.mapper")
public class MybatisPlusConfig {


    /**
     * mybatis-plus分页插件<br>
     * 文档:http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, GlobalConfig globalConfig) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactory.setConfiguration(configuration);
        PaginationInterceptor pagination = new PaginationInterceptor();
        sqlSessionFactory.setPlugins(pagination);
        sqlSessionFactory.setGlobalConfig(globalConfig);
        return sqlSessionFactory.getObject();
    }

    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig config = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setKeyGenerator(new DB2KeyGenerator());
        config.setDbConfig(dbConfig);
        return config;
    }
}

以上就是mybatisplus的相关总结,如有问题,欢迎留言讨论~

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/126704.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • android跨平台开发_手机游戏跨平台开发

    android跨平台开发_手机游戏跨平台开发安卓跨平台开发实践

  • Vim复制粘贴_vim复制粘贴命令

    Vim复制粘贴_vim复制粘贴命令原文地址:http://lsong17.spaces.live.com/blog/cns!556C21919D77FB59!603.entry内容:用vim这么久了,始终也不知道怎么在vim中使用系统粘贴板,通常要在网上复制一段代码都是先gedit打开文件,中键粘贴后关闭,然后再用vim打开编辑,真的不爽;上次论坛上有人问到了怎么在vim中使用系统粘贴板,印象里回复很多,有好几

  • c++基础知识入门_c语言刷屏代码

    c++基础知识入门_c语言刷屏代码往期文章分享点击跳转=>熬夜再战Android从青铜到王者-UI组件快速搭建App界面点击跳转=>熬夜再战Android从青铜到王者-几个适配方案点击跳转=>熬夜再战Android从青铜到王者-开发效率插件篇点击跳转=>Unity粒子特效系列-龙卷风预制体做好了,unitypackage包直接用!点击跳转=>姐姐喊我解锁套娃新技能:FairyGUI在Unity中实现List嵌套List/立体画廊等,玩出花儿来点击跳转=>Unity新手必备5款宝藏插件–价值上.

  • 海量数据处理的 Top K 相关问题

    海量数据处理的 Top K 相关问题

    2021年11月22日
  • GoogLeNet论文详解[通俗易懂]

    GoogLeNet论文详解[通俗易懂]GoogLeNet1.Introduction  得益于深度学习的优势和更强大的卷积神经网络的出现,图像分类和目标检测的准确率发生了令人意想不到的进步。在2014年的ILSVRC比赛中,GoogLeNet取得了第一名的成绩,所用模型参数不足AlexNet(2012年冠军)的1/12。论文题目《Goingdeeperwithconvolutions》中的deeper有两层含义…

  • 一个还不错的gridview 样式【Z】

    一个还不错的gridview 样式【Z】…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号