欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MyBatis-Plus简介和快速入门教程

程序员文章站 2022-07-01 08:18:03
目录一、mybatis-plus简介(来自官网)三、通用crud3.2 updatebyid(更新操作)一、mybatis-plus简介(来自官网)mybatis-plus,简称mp,是一个mybat...

 一、mybatis-plus简介(来自官网)

mybatis-plus,简称mp,是一个mybatis的增强工具,在mybatis的基础上只做增强不做修改,为简化开发、提高效率而生。

特性:

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 curd,性能基本无损耗,直接面向对象操作
  • 强大的 crud 操作:内置通用 mapper、通用 service,仅仅通过少量配置即可实现单表- 大部分 crud 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 lambda 形式调用:通过 lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 id 生成器 - sequence),可*配置,完美解决主键问题
  • 支持 activerecord 模式:支持 activerecord 形式调用,实体类只需继承 model 类即可进行强大的 crud 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( write once, use anywhere )
  • 内置代码生成器:采用代码或者 maven 插件可快速生成 mapper 、 model 、 service 、 controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 mybatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 list 查询
  • 分页插件支持多种数据库:支持 mysql、mariadb、oracle、db2、h2、hsql、sqlite、postgre、sqlserver 等多种数据库
  • 内置性能分析插件:可输出 sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、快速开始

步骤一、新建数据库表,写对应的javabean类。
首先我们还是使用我们之前mybatis建的student表吧。(这里,四个属性的名称前面的s_被我又去掉了)

MyBatis-Plus简介和快速入门教程

然后为我们的表格创建一个bean。

package com.example.po;

public class student {
    private integer id;
    private string name;
    private string email;
    private integer age;

    public student() {
    }

    public student(integer id, string name, string email, integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }

    public integer getid() {
        return id;
    }

    public void setid(integer id) {
        this.id = id;
    }

    public string getname() {
        return name;
    }

    public void setname(string name) {
        this.name = name;
    }

    public string getemail() {
        return email;
    }

    public void setemail(string email) {
        this.email = email;
    }

    public integer getage() {
        return age;
    }

    public void setage(integer age) {
        this.age = age;
    }

    @override
    public string tostring() {
        return "student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

步骤二、添加依赖

mybatis和mybatis-plus会自动维护我们的mybatis 以及mybatis-spring相关的依赖

 <dependencies>
        <!--mybatisplus-->
        <dependency>
            <groupid>com.baomidou</groupid>
            <artifactid>mybatis-plus</artifactid>
            <version>3.4.3</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <!--log4j-->
        <dependency>
            <groupid>log4j</groupid>
            <artifactid>log4j</artifactid>
            <version>1.2.17</version>
        </dependency>
        <!--c3p0-->
        <dependency>
            <groupid>com.mchange</groupid>
            <artifactid>c3p0</artifactid>
            <version>0.9.5.2</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
            <version>8.0.26</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-context</artifactid>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-orm</artifactid>
            <version>5.3.9</version>
        </dependency>
    </dependencies>

步骤三、写配置文件
mybatis的配置文件:
mybatis-config.xml

<?xml version="1.0" encoding="utf-8" ?>
<!doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

</configuration>

log4j.xml日志

<?xml version="1.0" encoding="utf-8"?>
<!doctype log4j:configuration public "-//log4j/log4j configuration//en" "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- 日志输出到控制台 -->
    <appender name="stdout" class="org.apache.log4j.consoleappender">
        <!--编码格式-->
        <param name="encoding" value="utf-8"/>
        <!-- 日志输出格式 -->
        <layout class="org.apache.log4j.patternlayout">
            <param name="conversionpattern" value="[%p][%d{yyyy-mm-dd hh:mm:ss sss}][%c]-[%m]%n"/>
        </layout>
    </appender>

    <logger name="java.sql">
        <level value ="debug"/>
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    </logger>

    <root>
        <level value="debug"/>
        <appender-ref ref="stdout"/>
    </root>
</log4j:configuration>

db.properties

jdbc.driver=com.mysql.cj.jdbc.driver
jdbc.url=jdbc:mysql://localhost/mybatis?usessl=false&servertimezone=utc
jdbc.username=root
jdbc.password=root

applicationcontext.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemalocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--数据源-->
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
        <property name="driverclass" value="${jdbc.driver}"/>
        <property name="jdbcurl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--事务管理器-->
    <bean id="datasourcetransactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
        <property name="datasource" ref="datasource"/>
    </bean>

    <!--基于注解的事务管理-->
    <tx:annotation-driven transaction-manager="datasourcetransactionmanager"/>

    <!--配置mybatisplus的mybatissqlsessionfactorybean-->
    <bean id="sqlsessionfactorybean" class="com.baomidou.mybatisplus.extension.spring.mybatissqlsessionfactorybean">
        <!--数据源-->
        <property name="datasource" ref="datasource"/>
        <property name="configlocation" value="classpath:mybatis-config.xml"/>
        <!--别名处理-->
        <property name="typealiasespackage" value="com.example.po"/>
    </bean>

    <!--配置mybatis扫描mapper接口的路径-->
    <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
        <property name="basepackage" value="com.example.dao"/>
    </bean>

</beans>

步骤四、集成mp(mybatis-plus,后边都直接简称mp)
mp的集成非常简单,对于spring,我们仅仅需要把mybatis自带的mybatissqlsessionfactory替换为mp自带的即可。也就是刚才applicationcontext.xml文件中的这一段:
如果是mybatis的话,那么class的值是org.mybatis.spring.sqlsessionfactorybean

MyBatis-Plus简介和快速入门教程

三、通用crud

准备完毕,现在我们可以开始进行我们的crud了。(开始爽了)
首先,说一下之前我们使用mybatis的做法吧:
步骤:
1、创建dao接口
2、写接口方法
3、创建mapper文件,并为每个接口方法写sql语句
4、在mybatis的主配置文件注册mapper

然后我们再说一下mp的做法:
步骤:
1、创建dao接口,继承basemapper<t>接口,<t>传入他对应的实体类。

就没了?!!!没错,就这一部,不需要写我们的xml文件。mp已经帮我们全都写好了。我们直接写测试代码:

3.1 insert(插入操作)

package com.example.text;

import com.example.dao.studentdao;
import com.example.po.student;
import org.junit.test;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

public class mytest {
    private applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");
    private studentdao studentdao = context.getbean("studentdao",studentdao.class);

    //通用插入操作
    @test
    public void testinsert(){
        //初始化student
        student student = new student(null,"林八","linba@163.com",23);
        int num = studentdao.insert(student);
        system.out.println("成功添加"+num+"条记录");
    }
}

执行后,看我们的数据库(添加成功)

MyBatis-Plus简介和快速入门教程

插入后,我们甚至可以直接获取自增的id值如下:

@test
    public void testinsert(){
        //初始化student
        student student = new student(null,"张飞","liubei@163.com",30);
        int num = studentdao.insert(student);
        system.out.println("成功添加"+num+"条记录");
        //插入操作执行后,我们可以获取自增的主键值
        int id = student.getid();
        system.out.println("插入的主键值为:"+id);
    }

数据库:

MyBatis-Plus简介和快速入门教程

控制台:

MyBatis-Plus简介和快速入门教程

3.2 updatebyid(更新操作)

直接传入一个student对象即可。(除id值外,其他值都可为空,为空的字段不会出现在sql语句中)
直接写测试方法:

  //通用更新操作
    @test
    public void testupdatebyid(){
        //初始化student
        student student = new student(1004,"关羽","guanyu@qq.com",29);
        int result = studentdao.updatebyid(student);
        system.out.println("成功修改"+result+"条记录");
    }

数据库:

MyBatis-Plus简介和快速入门教程

3.3 查询操作——各种select

通过id查询:selectbyid

 @test
    public void testselectbyid(){
        student student = studentdao.selectbyid(1007);
        system.out.println(student);
    }

显示:

MyBatis-Plus简介和快速入门教程

使用and查询单条记录:selectone(返回复数记录的话会报错)

@test
    public void testselectone(){
    	//写个匿名类,设置我们要查询的组合条件的实体类
        wrapper<student> stu = new wrapper<student>() {
            @override
            public student getentity() {
                return new student(null,"关羽",null,29);
            }

            @override
            public mergesegments getexpression() {
                return null;
            }

            @override
            public void clear() {

            }

            @override
            public string getsqlsegment() {
                return null;
            }
        };
        
        student student = studentdao.selectone(stu);
        system.out.println(student);
    }

结果:

MyBatis-Plus简介和快速入门教程

使用in通过id值查询多条记录(selectbatchids)

@test
    public void testselectbatchids(){
        list<integer> ids = new arraylist<>();
        ids.add(1001);
        ids.add(1002);
        list<student> students = studentdao.selectbatchids(ids);
        for (student stu:students){
            system.out.println(stu);
        }
    }

显示:

MyBatis-Plus简介和快速入门教程

传入map通过and查询若干条数据:selectbymap

 @test
    public void testselectbymap(){
        map<string,object> map = new hashmap<>();
        //map的键必须跟表中的列名相同
        map.put("s_name","张飞");
        map.put("s_age",28);
        list<student> students = studentdao.selectbymap(map);
        for (student stu:students){
            system.out.println(stu);
        }
    }

结果:

MyBatis-Plus简介和快速入门教程

3.4 删除操作——各种delete

  • 通过id删除记录:deletebyid
  • 通过多个id删除多条记录:deletebatchids
  • 通过and组合条件删除记录:deletebymap
  @test
    public void testdeletebyid(){
        int result = studentdao.deletebyid(1001);
        system.out.println("成功删除"+result+"条记录");
    }

    @test
    public void testdeletebatchids(){
        list<integer> ids = new arraylist<>();
        ids.add(1002);
        ids.add(1003);
        int result = studentdao.deletebatchids(ids);
        system.out.println("成功删除"+result+"条记录");
    }

    @test
    public void testdeletebymap(){
        map<string,object> map = new hashmap<>();
        map.put("s_id",1005);
        map.put("s_name","刘七");
        int result = studentdao.deletebymap(map);
        system.out.println("成功删除"+result+"条记录");
    }

依次执行上面的方法,控制台和数据库显示:

MyBatis-Plus简介和快速入门教程
MyBatis-Plus简介和快速入门教程
MyBatis-Plus简介和快速入门教程
MyBatis-Plus简介和快速入门教程
MyBatis-Plus简介和快速入门教程
MyBatis-Plus简介和快速入门教程

附加1:如果表名或者表中属性的名称与我们实体类的名称不同解决方法

假如现在,我们的表名叫mp_student
属性名分别叫s_id,s_name,s_email,s_age。
那么,我们就要在实体类
1、用@tablename对实体类进行标注
2、用@idname对主键进行标注
3、用@tablefield对非主键进行标注
如下:

package com.example.po;

import com.baomidou.mybatisplus.annotation.idtype;
import com.baomidou.mybatisplus.annotation.tablefield;
import com.baomidou.mybatisplus.annotation.tableid;
import com.baomidou.mybatisplus.annotation.tablename;

@tablename(value = "mp_student")
public class student {
    /*
    *   tableid标注这个是主键
    *   value值告诉mp这个主键在表中的属性名(相同其实也可以省略不写)
    *   type值有以下几个,分别表示:
    *   auto	数据库id自增
    *   none	无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 input)
    *   input	insert前自行set主键值
    *   assign_id	分配id(主键类型为number(long和integer)或string)(since 3.3.0),使用接口identifiergenerator的方法nextid(默认实现类为defaultidentifiergenerator雪花算法)
    *   assign_uuid	分配uuid,主键类型为string(since 3.3.0),使用接口identifiergenerator的方法nextuuid(默认default方法)
    * */
    @tableid(value = "s_id", type = idtype.auto)
    private integer id;
    @tablefield(value = "s_name")
    private string name;
    @tablefield(value = "s_email")
    private string email;
    @tablefield(value = "s_age")
    private integer age;

    public student() {
    }

    public student(integer id, string name, string email, integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }

    public integer getid() {
        return id;
    }

    public void setid(integer id) {
        this.id = id;
    }

    public string getname() {
        return name;
    }

    public void setname(string name) {
        this.name = name;
    }

    public string getemail() {
        return email;
    }

    public void setemail(string email) {
        this.email = email;
    }

    public integer getage() {
        return age;
    }

    public void setage(integer age) {
        this.age = age;
    }

    @override
    public string tostring() {
        return "student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

注意:设置主键的type=auto的话,必须要数据库中对主键设置自增,并设置自增的起始值才行。设置如下:
选择自己的数据库表,然后点击design table

MyBatis-Plus简介和快速入门教程

选中主键,然后点击下面的auto increment(自增)

MyBatis-Plus简介和快速入门教程

点击option菜单项,设置自增的起始值。

MyBatis-Plus简介和快速入门教程

顺便说下,tablename和tablefield这两个注释,他们也有自己的其他属性值:

点击查看官方tablename属性值介绍

点击查看官方tablefield属性值介绍

到此这篇关于mybatis-plus简介和快速入门教程的文章就介绍到这了,更多相关mybatis-plus入门内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: MyBatis-Plus 入门