草庐IT

Mybatis-Plus

欢迎来到BYL的博客 2023-04-16 原文

MyBatis Plus

国产的开源框架,基于 MyBatis

核心功能就是简化 MyBatis 的开发,提高效率。

MyBatis Plus 快速上手 官网快速上手案例

Spring Boot(2.3.0) + MyBatis Plus(国产的开源框架,并没有接入到 Spring 官方孵化器中)

1、创建 Maven 工程

2、pom.xml 引入 MyBatis Plus 的依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

3、创建实体类

package com.southwind.mybatisplus.entity;

import lombok.Data;

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

4、创建 Mapper 接口

package com.southwind.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.southwind.mybatisplus.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

5、配置数据库application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/ssmbooks?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:com/bai/mapper/xml/*.xml
server:
  port: 8181

6、启动类需要添加 @MapperScan("mapper所在的包"),否则无法加载 Mppaer bean。

package com.southwind.mybatisplus;

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

@SpringBootApplication
@MapperScan("com.southwind.mybatisplus.mapper")
public class MybatisplusApplication {

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

}

7、测试

package com.southwind.mybatisplus.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class UserMapperTest {

    @Autowired
    private UserMapper mapper;

    @Test
    void test(){
        mapper.selectList(null).forEach(System.out::println);
    }

}

Mybatis-Plus常用注解

@TableName

映射数据库的表名

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value = "user")
public class Account {
    private Integer id;
    private String name;
    private Integer age;
}

@TableId

设置主键映射:

value 映射主键字段名

type 设置主键类型,主键的生成策略,

AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
描述
AUTO 数据库自增
NONE MP set 主键,雪花算法实现
INPUT 需要开发者手动赋值
ASSIGN_ID MP 分配 ID,Long、Integer、String
ASSIGN_UUID 分配 UUID,Strinig

INPUT 如果开发者没有手动赋值,则数据库通过自增的方式给主键赋值,如果开发者手动赋值,则存入该值。

AUTO 默认就是数据库自增,开发者无需赋值。

ASSIGN_ID MP 自动赋值,雪花算法。

ASSIGN_UUID 主键的数据类型必须是 String,自动生成 UUID 进行赋值

@TableField

映射非主键字段:

value 映射字段名

exist 表示是否为数据库字段 false,如果实体类中的成员变量在数据库中没有对应的字段,则可以使用 exist,VO、DTO

select 表示是否查询该字段

fill 表示是否自动填充,将对象存入数据库的时候,由 MyBatis Plus 自动给某些字段赋值,create_time、update_time

实体类中添加成员变量

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

@Data
@TableName(value = "user")
public class User {
    @TableId
    private String id;
    @TableField(value = "name",select = false)
    private String title;
    private Integer age;
    @TableField(exist = false)
    private String gender;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

@TableLogic

映射逻辑删除
1、数据表添加 deleted 字段

2、实体类添加注解
@TableLogic private Integer deleted;
3、application.yml 添加配置

global-config:
  db-config:
    logic-not-delete-value: 0
    logic-delete-value: 1

查询

	mapper.selectList(null);
QueryWrapper wrapper = new QueryWrapper();
        Map<String,Object> map = new HashMap<>();
        map.put("name","小红");
        map.put("age",3);
        wrapper.allEq(map);
        wrapper.gt("age",2);
        wrapper.ne("name","小红");
        wrapper.ge("age",2);

//like '%小'
        wrapper.likeLeft("name","小");
//like '小%'
        wrapper.likeRight("name","小");

//inSQL
        wrapper.inSql("id","select id from user where id < 10");
        wrapper.inSql("age","select age from user where age > 3");

        wrapper.orderByDesc("age");

        wrapper.orderByAsc("age");
        wrapper.having("id > 8");

mapper.selectList(wrapper).forEach(System.out::println);
        System.out.println(mapper.selectById(7));
        mapper.selectBatchIds(Arrays.asList(7,8,9)).forEach(System.out::println);

//Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
        Map<String,Object> map = new HashMap<>();
        map.put("id",7);
        mapper.selectByMap(map).forEach(System.out::println);

QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
        System.out.println(mapper.selectCount(wrapper));

        //将查询的结果集封装到Map中
        mapper.selectMaps(wrapper).forEach(System.out::println);
        System.out.println("-------------------");
        mapper.selectList(wrapper).forEach(System.out::println);

//分页查询
        Page<User> page = new Page<>(2,2);
        Page<User> result = mapper.selectPage(page,null);
        System.out.println(result.getSize());
        System.out.println(result.getTotal());
        result.getRecords().forEach(System.out::println);

        Page<Map<String,Object>> page = new Page<>(1,2);
        mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);

        mapper.selectObjs(null).forEach(System.out::println);


System.out.println(mapper.selectOne(wrapper));

自定义 SQL(多表关联查询)

package com.southwind.mybatisplus.entity;

import lombok.Data;

@Data
public class ProductVO {
    private Integer category;
    private Integer count;
    private String description;
    private Integer userId;
    private String userName;
}
package com.southwind.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.southwind.mybatisplus.entity.ProductVO;
import com.southwind.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {
    @Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")
    List<ProductVO> productList(Integer id);
}

添加

User user = new User();
user.setTitle("小明");
user.setAge(22);
mapper.insert(user);
System.out.println(user);

删除

//mapper.deleteById(1);
//        mapper.deleteBatchIds(Arrays.asList(7,8));
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("age",14);
//        mapper.delete(wrapper);

Map<String,Object> map = new HashMap<>();
map.put("id",10);
mapper.deleteByMap(map);

修改

//        //update ... version = 3 where version = 2
//        User user = mapper.selectById(7);
//        user.setTitle("一号");
//
//        //update ... version = 3 where version = 2
//        User user1 = mapper.selectById(7);
//        user1.setTitle("二号");
//
//        mapper.updateById(user1);
//        mapper.updateById(user);

User user = mapper.selectById(1);
user.setTitle("小红");
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",22);
mapper.update(user,wrapper);

有关Mybatis-Plus的更多相关文章

  1. PLUS模型和InVEST模型生态系统服务多情景模拟预测、ArcGIS空间数据处理、空间分析与制图、土地利用时空变化 - 2

    查看原文>>>基于”PLUS模型+“生态系统服务多情景模拟预测实践技术应用目录第一章、理论基础与软件讲解第二章、数据获取与制备第三章、土地利用格局模拟第四章、生态系统服务评估第五章、时空变化及驱动机制分析第六章、论文撰写技巧及案例分析基于ArcGISPro、Python、USLE、INVEST模型等多技术融合的生态系统服务构建生态安全格局基于生态系统服务(InVEST模型)的人类活动、重大工程生态成效评估、论文写作等具体应用基于ArcGISPro、R、INVEST等多技术融合下生态系统服务权衡与协同动态分析实践应用    本文从数据、方法、实践三方面对生态系统服务多情景预测进行讲解。内容涵盖多

  2. ruby-on-rails - rails : Plus sign in GET-Request replaced by space - 2

    在Rails3(Ruby1.9.2)中我发送一个请求StartedGET"/controller/action?path=/41_+"但是参数列表是这样的:{"path"=>"/41_","controller"=>"controller","action"=>"action"}这里出了什么问题?-、*或.符号工作正常,只是+将被空格替换。 最佳答案 这是正常的URL编码,theplussignisashorthandforaspace:Withinthequerystring,theplussignisreservedasshor

  3. javascript - urllib.quote_plus() 在 JavaScript 中等效 - 2

    尝试从Python移植一段代码:my_input="this&is£sometext"encoded_input=urllib.quote_plus(str(my_input))...到JavaScript:varmy_input="this&is£sometext";encoded_input=encodeURIComponent(my_input);细微差别是urllib.quote_plus()会将空格转换为+而不是%20(link).只是想知道是否有人可以提供任何想法。目前正在处理这个......varmy_input="this&is£sometext";encoded_in

  4. javascript - iPhone 8、iPhone 8 Plus 和 iPhone X 的用户代理字符串是什么? - 2

    在设备检测中,新iPhone8、iPhone8Plus和iPhoneX的用户代理是什么? 最佳答案 这是他们的用户代理字符串:Mozilla/5.0(iPhone;CPUOS11_0likeMacOSX)AppleWebKit/604.1.25(KHTML,likeGecko)Version/11.0Mobile/15A372Safari/604.1来源:iOS11固件型号为15A372。Hereisauseragent来自iOS11的测试版,其中包含AppleWebKit和Safari版本号。

  5. 基于Spring注解 + MyBatis + Servlet 实现数据库交换的小小Demo - 2

    基于Spring注解+MyBatis+Servlet实现数据库交换的小小Demo第一步创建web项目,这一步省略,有不会的可以参考之前发布的文档第二步配置pom.xml文件dependencies>dependency>groupId>org.springframeworkgroupId>artifactId>spring-contextartifactId>version>5.2.9.RELEASEversion>dependency>dependency>groupId>org.springframeworkgroupId>artifactId>spring-aspectsartifact

  6. javascript - 我想在点击 Google Plus 按钮时调用 Google Plus 回调函数 - 2

    我在我的项目[内置CodeIgniter]中使用了GooglePlus按钮。我在这里添加了以下代码。然后我添加了Google提供的Javascript代码。(function(){varpo=document.createElement('script');po.type='text/javascript';po.async=true;po.src='https://apis.google.com/js/client:plusone.js';vars=document.getElementsByTagName('script')[0];s.parentNode.insertBefore

  7. springboot整合mybatis代码快速生成 - 2

    特别说明:本次项目整合基于idea进行的,如果使用Eclipse可能操作会略有不同,不过总的来说不影响。springboot整合之如何选择版本及项目搭建springboot整合之版本号统一管理 springboot整合mybatis-plus+durid数据库连接池springboot整合swaggerspringboot整合mybatis代码快速生成springboot整合之统一结果返回springboot整合之统一异常处理springboot整合之Validated参数校验 springboot整合之logback日志配置springboot整合pagehelper分页springboot

  8. javascript - Google Plus 中奇怪的 JSON 响应 - 2

    当我在GooglePlus中调试错误时(从Yahoo导入FB联系人时)我发现了奇怪的JSON响应:)]}'[[["er",,,,,500],["e",2,,,57]],'45932b7d6d6dc08e']它是JSONP的变体吗?让我想起了一个SQL注入(inject)而不是......那么,结束括号和开头引号的目的是什么? 最佳答案 它基本上是删除了空值并在开头添加了垃圾以阻止XSRF的JSON。这是一些将对其进行解码的PHP代码(来self正在处理的非官方GooglePlusAPI)。https://github.com/jms

  9. javascript - Casperjs/Phantomjs - 在加载 google plus 主页时挂起 - 2

    成功登录后,我尝试导航到https://plus.google.com/u/0/?tab=wX但casperjs挂起。最后的输出是:[debug][phantom]Navigationrequested:url=https://clients6.google.com/static/proxy.html?jsh=m;/_/scs/apps-static/_/js/k=oz.gapi.en.Z6gj5B0lzyA.O/m=__features__/am=IQ/rt=j/d=1/t=zcms/rs=AItRSTPU0_gqMrtQ831rDdqYv8Z1ZnxcbA#parent=https

  10. javascript - Django 表单 - django-bootstrap-datepicker-plus 不呈现日期选择器 - 2

    我在尝试渲染时遇到一些不便django-bootstrap-datepicker-plus小部件根据thisanswer.一切正常,但Datepicker没有出现。我的Django版本是1.10.7,我使用的第三方应用是:DjangoBootstrap3(pipinstalldjango-bootstrap3)DjangoBootstrapDatepickerPlus(pipinstalldjango-bootstrap-datepicker-plus)这是我的forms.py,我覆盖了DateInput类以根据我的需要对其进行自定义。fromdjangoimportformsfrom

随机推荐