mybatis-plus快速入门

1. 首先我们要建立一个Maven项目,pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>top.itreatment</groupId>
    <artifactId>mybatis-plus-study</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-plus-study</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--    java开发的工具包,使得类更加简洁    -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--    扩展插件,mybatis-plus,该依赖会自动导入mybatis    -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <!--   连接mysql 驱动   -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
    </dependencies>

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

2. 配置文件application.yml如下:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&useSSL=false&characterEncoding=utf8
    username: root
    password:

3. 实体类:

import lombok.Data;

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

4. 实体类对应的mapper接口

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import top.itreatment.mybatisplusstudy.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

完成上面的准备就可以开始使用了

下面是使用内置对象的小例子:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.minidev.json.JSONUtil;
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 top.itreatment.entity.UserEntity;
import top.itreatment.mapper.UserDao;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MainTest {


    @Autowired
    private UserDao userDao;

    /**
     * 测试插入操作
     * Preparing: INSERT INTO user ( name, age, email ) VALUES ( ?, ?, ? )
     * Parameters: zjb(String), 24(Integer), 5924(String)
     */
    @Test
    public void testInsert01() {
        UserEntity zjb = UserEntity.builder().name("zjb").age(24).email("5924").build();
        int insert = userDao.insert(zjb);
        System.out.println("insert = " + insert);
        System.out.println("zjb.getId() = " + zjb.getId());
    }


    /**
     * 测试更新操作
     * Preparing: UPDATE user SET name=?, age=?, email=? WHERE id=?
     * Parameters: YJN(String), 24(Integer), 5924(String), 6(Long)
     */
    @Test
    public void testUpdate01() {
        UserEntity zjb = UserEntity.builder().id(6L).name("YJN").age(24).email("5924").build();
        int i = userDao.updateById(zjb);
        System.out.println("i = " + i);
    }

    /**
     * 测试更新操作02
     * Preparing: UPDATE user SET name=? WHERE id=?
     * Parameters: zjb(String), 10(Long)
     */
    @Test
    public void testUpdate02() {
        UpdateWrapper<UserEntity> userEntityUpdateWrapper = new UpdateWrapper<>();
        userEntityUpdateWrapper.set("name", "zjb");
        userEntityUpdateWrapper.setEntity(UserEntity.builder().id(10L).build());
        userDao.update(userEntityUpdateWrapper.getEntity(), userEntityUpdateWrapper);
    }


    /**
     * 测试删除操作01
     * Preparing: DELETE FROM user WHERE id=?
     * Parameters: 1(Long)
     * Updates: 1
     */
    @Test
    public void testDelete01() {
        userDao.deleteById(1L);
    }

    /**
     * 测试删除操作02
     * Preparing: DELETE FROM user WHERE id IN ( ? , ? )
     * Parameters: 2(Long), 3(Long)
     * Updates: 2
     */
    @Test
    public void testDelete02() {
        userDao.deleteBatchIds(Arrays.asList(2L,3L));
    }

    /**
     * 测试删除操作03
     * Preparing: DELETE FROM user WHERE name = ?
     * Parameters: zjb(String)
     * Updates: 2
     */
    @Test
    public void testDelete03() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name","zjb");
        userDao.deleteByMap(hashMap);
    }

    /**
     *  测试删除操作04
     *  Preparing: DELETE FROM user WHERE name=? 
     *  Parameters: YJN(String)
     *  Updates: 1
     */
    @Test
    public void testDelete04() {
        UpdateWrapper<UserEntity> wrapper = new UpdateWrapper<>();
        wrapper.setEntity(UserEntity.builder().name("YJN").build());
        userDao.delete(wrapper);
    }

    /**
     * 测试查询操作01
     * Preparing: SELECT id,name,age,email FROM user
     * Parameters:
     */
    @Test
    public void testSelect01() {
        List<UserEntity> userEntities = userDao.selectList(null);
        userEntities.forEach(System.out::println);
    }

    /**
     * 测试查询操作02
     * Preparing: SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
     * Parameters: zjb(String), 24(Integer)
     * <p>
     * Preparing: SELECT id,name,age,email FROM user WHERE name=? AND age=?
     * Parameters: zjb(String), 24(Integer)
     * SelectOne sql查到的结果只能是一条或是零条,多条会报错
     */
    @Test
    public void testSelect02() {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("name","zjb");
//        wrapper.eq("age",24);
        wrapper.setEntity(UserEntity.builder().name("zjb").age(24).build());
        userDao.selectOne(wrapper);
    }

    /**
     * 测试查询操作03
     * Preparing: SELECT id,name,age,email FROM user WHERE name = ?
     * Parameters: zjb(String)
     * Total: 2
     */
    @Test
    public void testSelect03() {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("name", "zjb");
        userDao.selectList(wrapper);
    }

    /**
     * 测试查询操作04
     * Preparing: SELECT id,name,age,email FROM user WHERE name = ? AND email = ?
     * Parameters: zjb(String), 5924(String)
     * Total: 2
     */
    @Test
    public void testSelect04() {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("name", "zjb");
        wrapper.eq("email", "5924");
        userDao.selectList(wrapper);
    }

    /**
     * 测试查询操作05
     * Preparing: SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
     * Parameters: 1(Long), 2(Long), 3(Long)
     * Total: 3
     */
    @Test
    public void testSelect05() {
        userDao.selectBatchIds(Arrays.asList(1L, 2L, 3L));
    }

    /**
     * 测试查询操作06
     * Preparing: SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
     * Parameters: Parameters: zjb(String), 24(Integer)
     * Total: 1
     */
    @Test
    public void testSelect06() {
        Map<String, Object> emptyMap = new HashMap();
//        key 为列名
        emptyMap.put("name", "zjb");
        emptyMap.put("age", 24);
        userDao.selectByMap(emptyMap);
    }

    /**
     * 测试查询操作07
     * Preparing: SELECT id,name,age,email FROM user
     * Parameters:
     * Total: 11
     */
    @Test
    public void testSelect07() {
        IPage<UserEntity> userEntityIPage = userDao.selectPage(new Page<>(1, 5), null);
        userEntityIPage.getRecords().forEach(System.out::println);
    }
}
 * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.baomidou.mybatisplus.core.enums;

/**
 * MybatisPlus 支持 SQL 方法
 *
 * @author hubin
 * @since 2016-01-23
 */
public enum SqlMethod {
    /**
     * 插入
     */
    INSERT_ONE("insert", "插入一条数据(选择字段插入)", "<script>\nINSERT INTO %s %s VALUES %s\n</script>"),

    /**
     * 删除
     */
    DELETE_BY_ID("deleteById", "根据ID 删除一条数据", "<script>\nDELETE FROM %s WHERE %s=#{%s}\n</script>"),
    DELETE_BY_MAP("deleteByMap", "根据columnMap 条件删除记录", "<script>\nDELETE FROM %s %s\n</script>"),
    DELETE("delete", "根据 entity 条件删除记录", "<script>\nDELETE FROM %s %s %s\n</script>"),
    DELETE_BATCH_BY_IDS("deleteBatchIds", "根据ID集合,批量删除数据", "<script>\nDELETE FROM %s WHERE %s IN (%s)\n</script>"),

    /**
     * 逻辑删除
     */
    LOGIC_DELETE_BY_ID("deleteById", "根据ID 逻辑删除一条数据", "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>"),
    LOGIC_DELETE_BY_MAP("deleteByMap", "根据columnMap 条件逻辑删除记录", "<script>\nUPDATE %s %s %s\n</script>"),
    LOGIC_DELETE("delete", "根据 entity 条件逻辑删除记录", "<script>\nUPDATE %s %s %s %s\n</script>"),
    LOGIC_DELETE_BATCH_BY_IDS("deleteBatchIds", "根据ID集合,批量逻辑删除数据", "<script>\nUPDATE %s %s WHERE %s IN (%s) %s\n</script>"),

    /**
     * 修改
     */
    UPDATE_BY_ID("updateById", "根据ID 选择修改数据", "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>"),
    UPDATE_ALL_COLUMN_BY_ID("updateAllColumnById", "根据ID 选择修改数据", "<script>\nUPDATE %s SET %s WHERE %s=#{%s} %s\n</script>"),
    UPDATE("update", "根据 whereEntity 条件,更新记录", "<script>\nUPDATE %s %s %s %s\n</script>"),

    /**
     * 逻辑删除 -> 修改
     */
    LOGIC_UPDATE_BY_ID("updateById", "根据ID 修改数据", "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>"),

    /**
     * 查询
     */
    SELECT_BY_ID("selectById", "根据ID 查询一条数据", "SELECT %s FROM %s WHERE %s=#{%s}"),
    SELECT_BY_MAP("selectByMap", "根据columnMap 查询一条数据", "<script>\nSELECT %s FROM %s %s\n</script>"),
    SELECT_BATCH_BY_IDS("selectBatchIds", "根据ID集合,批量查询数据", "<script>\nSELECT %s FROM %s WHERE %s IN (%s)\n</script>"),
    SELECT_ONE("selectOne", "查询满足条件一条数据", "<script>\nSELECT %s FROM %s %s %s\n</script>"),
    SELECT_COUNT("selectCount", "查询满足条件总记录数", "<script>\nSELECT COUNT(%s) FROM %s %s %s\n</script>"),
    SELECT_LIST("selectList", "查询满足条件所有数据", "<script>\nSELECT %s FROM %s %s %s\n</script>"),
    SELECT_PAGE("selectPage", "查询满足条件所有数据(并翻页)", "<script>\nSELECT %s FROM %s %s %s\n</script>"),
    SELECT_MAPS("selectMaps", "查询满足条件所有数据", "<script>\nSELECT %s FROM %s %s %s\n</script>"),
    SELECT_MAPS_PAGE("selectMapsPage", "查询满足条件所有数据(并翻页)", "<script>\nSELECT %s FROM %s %s %s\n</script>"),
    SELECT_OBJS("selectObjs", "查询满足条件所有数据", "<script>\nSELECT %s FROM %s %s %s\n</script>"),

    /**
     * 逻辑删除 -> 查询
     */
    LOGIC_SELECT_BY_ID("selectById", "根据ID 查询一条数据", "SELECT %s FROM %s WHERE %s=#{%s} %s"),
    LOGIC_SELECT_BATCH_BY_IDS("selectBatchIds", "根据ID集合,批量查询数据", "<script>\nSELECT %s FROM %s WHERE %s IN (%s) %s\n</script>");

    private final String method;
    private final String desc;
    private final String sql;

    SqlMethod(String method, String desc, String sql) {
        this.method = method;
        this.desc = desc;
        this.sql = sql;
    }

    public String getMethod() {
        return method;
    }

    public String getDesc() {
        return desc;
    }

    public String getSql() {
        return sql;
    }

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