springboot集成mybatisplus的用法

2023-10-27,,

这篇文章主要介绍“springboot集成mybatisplus的用法”,在日常操作中,相信很多人在springboot集成mybatisplus的用法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”springboot集成mybatisplus的用法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

介绍:

         Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。(摘自mybatis-plus官网)Mybatis虽然已经给我们提供了很大的方便,但它还是有不足之处,MP的存在就是为了稍稍弥补Mybatis的不足。在我们使用Mybatis时会发现,每当要写一个业务逻辑的时候都要在DAO层写一个方法,再对应一个SQL,即使是简单的条件查询、即使仅仅改变了一个条件都要在DAO层新增一个方法,针对这个问题,MP这样一个框架,一种集Mybatis与Hibernate的优点一起的框架。它提供了Hibernate的单表CURD操作的方便同时,又保留了Mybatis的特性。

本章只教大家怎么使用MybatisPlus,如果想深入了解底层是怎么实现的可以去官网下载源代码进行解读。

一、创建项目

  这里就不一步一步来了,我直接给出创建后的项目结构,在本章的最后我会给出源码地址需要看效果的可以进行下载。

二、引入依赖

<?xml version="1.0">

 三、编辑application.yml

server:
  port: 8080

spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    username: root
    password: dacian821
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.cdq.springboot_mybatisplus.domain

四、逆向生成pojo,mapper

 创建generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <properties resource="application.yml"/>
    <classPathEntry location="D:/develop/maven_repository/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
        </plugin>
        <!-- 注释 -->
        <commentGenerator>
            <!-- 是否生成注释代时间戳 -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>
        <!-- JDBC连接 -->
        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"
                userId="root"
                password="dacian821">
        </jdbcConnection>
        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.cdq.springboot_mybatisplus.dao.domain" targetProject="src/main/java"/>
        <!-- 生成mapper xml文件 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
        <!-- 生成mapper xml对应Client-->
        <javaClientGenerator targetPackage="com.cdq.springboot_mybatisplus.dao.mapper" targetProject="src/main/java"
                             type="XMLMAPPER"/>
        <!-- 配置表信息 -->
        <table tableName="%">
            <!--mysql 配置-->
            <generatedKey column="id" sqlStatement="Mysql"/>
            <!--oracle 配置-->
            <!--<generatedKey column="id" sqlStatement="select SEQ_{1}.nextval from dual" identity="false" type="pre"/>-->
        </table>
    </context>
</generatorConfiguration>

maven运行generator

生成完后的项目结构如下

五、整合mybatisplus

创建service接口以及service实现类

package com.cdq.springboot_mybatisplus.service;

import com.cdq.springboot_mybatisplus.dao.domain.Person;

import java.util.List;

public interface PersonService {

    List<Person> getPerson();

    boolean insert(Person person);
}
package com.cdq.springboot_mybatisplus.service.impl;

import com.cdq.springboot_mybatisplus.dao.domain.Person;
import com.cdq.springboot_mybatisplus.dao.mapper.PersonMapper;
import com.cdq.springboot_mybatisplus.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;

    @Override
    public List<Person> getPerson() {
        return personMapper.selectAll();
    }

    @Override
    public boolean insert(Person person) {
        int insert = personMapper.insert(person);
        if (insert >= 1) {
            return true;
        }
        return false;
    }
}

创建Controller

package com.cdq.springboot_mybatisplus.controller;

import com.cdq.springboot_mybatisplus.dao.domain.Person;
import com.cdq.springboot_mybatisplus.service.PersonService;
import com.cdq.springboot_mybatisplus.service.impl.PersonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    PersonService personService;

    @RequestMapping("/findAllPerson")
    List<Person> findAllPerson() {
        return personService.getPerson();
    }

    boolean insertPerson(Person person) {

        return personService.insert(person);
    }

}

这里我的mapper并不要写sql,一些简单的sqlmybatiplus都给封装好了,节省了许多开发时间,如果是一些复杂的sql,也可以通过写原生sql来实现

插入一些数据

package com.cdq.springboot_mybatisplus;

import com.cdq.springboot_mybatisplus.dao.domain.Person;
import com.cdq.springboot_mybatisplus.service.PersonService;
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.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisplusApplicationTests {

    @Autowired
    PersonService personService;

    @Test
    public void contextLoads() {
        for (int i = 1; i <= 30; i++) {
            Person person = new Person();
            person.setId(i);
            person.setUsername("zhangsan" + i);
            person.setPassword("zs"+i);
            person.setAge(String.valueOf(i));
            person.setNickname("张三" + i);
            if (i % 2 == 0) {
                person.setSex("男");
            } else {
                person.setSex("女");
            }
            personService.insert(person);

        }


    }

}

查看数据库

运行SpringbootMybatisplusApplication主函数

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.cdq.springboot_mybatisplus.dao.mapper")
public class SpringbootMybatisplusApplication {

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

}

访问http://localhost:8080/person/findAllPerson

 下面给出mybatisplus封装的一些方法,这些方法具体怎么使用,感兴趣的小伙伴可以查看下源代码,mybatisplus还有一个强大的分页功能,如果有兴趣也可以去学习http://mp.baomidou.com

demo项目地址:https://gitee.com/chendequan0821/springboot_mybatisplus.git

到此,关于“springboot集成mybatisplus的用法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注本站网站,小编会继续努力为大家带来更多实用的文章!

《springboot集成mybatisplus的用法.doc》

下载本文的Word格式文档,以方便收藏与打印。