首页 > 其他分享 >MyBatis-Plus【启程篇】

MyBatis-Plus【启程篇】

时间:2022-09-30 11:10:30浏览次数:78  
标签:启程 name Plus user MyBatis import com public


Mybatis-Plu只为增强而生

一、初始MyBatis-Plus

官方网址:​​https://baomidou.com/​

MyBatis-Plus【启程篇】_数据库


官方对MyBatis-Plus的解释: MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 ​​MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。​

总结: MP可以看作是MyBatis的好大哥。黑风寨的二把手,李云龙的和尚。魂斗罗的2P。有了MP,MyBatis可以不再写xxxmapper.xml便可以实现对数据库的持久化操作。可谓是便捷省事。

二、如何使用

在这里都是参考官网的教程,如有遗漏可移步官网参考,不喜勿喷,礼貌学习。

1、环境准备

  1. jdk1.8
  2. SpringBoot/Spring【官方推荐SpringBoot】
  3. Maven3.6.6
  4. Eclipse

2、新建数据库

既然是持久层矿建MyBatis的增强工具,那么必然需要一个数据库来进行相关的操作。

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);

为了方便测试,所以往数据库中新加一些数据,方便测试。

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

3、新建SpringBoot项目,并前期工作

  1. SpringBoot
  2. MySQL/Oracel
  3. MyBtais-PLUS
  4. Lombok
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

连接数据库配置文件以及SQL日志

spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=UTF-8&useSSL=true&useUnicode=true&serverTimezone=UTC
username: root
password: 123456

mybatis-plus:
configuration:
log-impl:

新建几个包:mapper、servcie、test、pojo…具体的项目目录结构如下:

MyBatis-Plus【启程篇】_java_02

4、编写各层代码

pojo层对数据表的实体进行封装

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class User {
private Long id;
private String name;
private Integer age;
private String email;

public User(String name, Integer age, String email) {
super();
this.name = name;
this.age = age;
this.email = email;
}
}

1️⃣通用Mapper

mapper层使用MP的通用Mapper进行操作,需要注意的是: 使用MP的通用Mapper必须要​​继承BaseMapper的这个类​​,这个类是有泛型的,反省对应着你的数据库的POJO类。

@Repository("userMapper")
public interface UserMapper extends BaseMapper<User>{
}

2️⃣通用Service

MP的通用Service是MP所提供的一种对原始mapper层的CRUD的封装调用
使用:

  1. 想要使用MyBatis-Plus的通用Service,首先我们需要写一个Service,然后继承MyBatis-Plus的通用Service(IService)。
  2. 然后再写一个ServiceImpl并且继承MyBatis-Plus的ServiceImpl<M extends BaseMapper, T>,当然还要实现我们写的Service。

1、

public interface IUserService extends IService<User>{
}

2、

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper , User> implements IUserService{
}

5、在启动类上加@MapperScann注解扫描mapper的包

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

@SpringBootApplication
// 扫描Mapper接口所在的包
@MapperScan("com.wei.mapper")
public class DhcMpProjectApplication {
public static void main(String[] args) {
SpringApplication.run(DhcMpProjectApplication.class, args);
}
}

6、编写测试类进行测试

package com.wei;

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

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

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wei.mapper.UserMapper;
import com.wei.pojo.User;

@SpringBootTest
public class MyTest {
// 注入Mapper的Bean
@Autowired
private UserMapper userMapper;

/**
* 新增数据 参数是一个实体对象
*/
@Test
public void test2() {
// 新增用户信息 INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
User user = new User("joker",23,"[email protected]");
int insert = userMapper.insert(user);
System.out.println("成功插入"+insert+"条数据");
// 在MyBatis里默认是使用雪花算法创建id 不会默认使用数据库里面的自增主键
System.out.println("id:"+user.getId());
}

/**
* 通过id删除数据
*/
@Test
public void test3() {
// 根据id删除 DELETE FROM user WHERE id=?
int deleteById = userMapper.deleteById(1529380500983910401L);
System.out.println("成功删除"+deleteById);
}

/**
* 通过map条件集合删除
*/
@Test
public void test4() {
// 根据条件删除数据 可以删除多个 DELETE FROM user WHERE name = ? AND age = ?
Map<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 23);
int deleteByMap = userMapper.deleteByMap(map);
System.out.println("删除了"+deleteByMap);
}

/**
* 批量删除
*/
@Test
public void test5() {
// 批量删除 DELETE FROM user WHERE id IN ( ? , ? )
Collection<Long> ids = new ArrayList<>();
ids.add(5L);
ids.add(2L);
int deleteBatchIds = userMapper.deleteBatchIds(ids);
System.out.println("删除了"+deleteBatchIds+"条数据");
}

/**
* 修改方法 参数为一个实体对象
*/
@Test
public void test6() {
// 根据id修改数据 UPDATE user SET name=?, age=?, email=? WHERE id=?
User user = new User(1L,"koppy",45,"[email protected]");
int updateById = userMapper.updateById(user);
System.out.println("修改了"+updateById+"条数据");
}

/**
* 查询方法 参数是一个条件warpper
*/
@Test
public void test7() {
List<Long> list = Arrays.asList(1L,2L,3L);
List<User> selectBatchIds = userMapper.selectBatchIds(list);
selectBatchIds.forEach(System.out::println);
}

/**
* 查询方法 参数是一个条件map
*/
@Test
public void test8() {
Map<String, Object> maps =new HashMap<>();
maps.put("name", "koppy");
maps.put("age", 45);
List<User> selectByMap = userMapper.selectByMap(maps);
selectByMap.forEach(System.out::println);
}

/**
* 查询方法 参数是一个条件warpper
*/
@Test
public void test9() {
Map<String, Object> maps =new HashMap<>();
maps.put("name", "koppy");
maps.put("age", 45);

List<User> selectByMap = userMapper.selectList(null);
selectByMap.forEach(System.out::println);
}
}

至此,MP的入门就到此为止了!

三、 总结:

  1. 对于MP的使用,可以帮助我们达到快速开发的目的,但是正所谓任何事物都有其双面性,我们往往只关注其便捷,有利的一面,却忽略了他的前期工作,在学此篇之前,我们必须要熟练掌握JDBC的所有操作以及数据库的相关知识。
  2. 在对MP的使用上,如果采用SpringBoot进行操作,必须要在起动类上加上MapperScan的注解
  3. 使用通用Mapper需要继承BaseMapper<T Entity >
  4. 使用通用Service 需要在接口上继承IService<T Entity>的接口,同时还要再实现类上继承ServiceImpl<M extends BaseMapper<T>, T>接口,同时实现 IService


标签:启程,name,Plus,user,MyBatis,import,com,public
From: https://blog.51cto.com/u_14957231/5725611

相关文章

  • MyBatis-缓存
    MyBatis缓存缓存的目的就是为了提高执行效率**内存:**不能永久存储数据,我们都知道内存他是​​断电即丢失​​​的,我们要想把数据永久存储,可以写入到磁盘上,但是缺点就是慢,而......
  • MyBatis加载Mapper映射文件的方式
    MyBatis加载Mapper的映射文件的方式我们都知道MyBatis是一款半自动的ORM框架,它的特点就是具有灵活的sql操作MyBatis是利用mapper的映射文件,来将数据库的中字段与Java的属性......
  • MYBatis-动态SQL
    MyBatis动态SQL什么是动态SQL?官方给出动态SQL的解释是一个基于OGNL的表达式,MyBatis3替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少......
  • MyBatis批量修改-Oracel
    MyBatis批量修改再利用MyBatis操作Oracle实现批量的修改操做的时候,需要用到存储过程的知识点批量修改,不同于批量的插入,批量修改可以同时操作不同表,但是如何保证他们是在同......
  • MyBatis-Plus 条件查询器
    MyBatis-Plus剩余内容​​本篇的主要代码依赖于之前的通用Mapper和通用Service篇​​前两个星期忙着转正的事情,比较忙。所以快两个周每太更新博客,这周末抓紧时间把剩余的MP......
  • SpringBoot之Mybatis开启SQL记录和Pagehelper
    配置mybatismybatis:#mapper路径mapper-locations:classpath:mapper/*.xmlconfiguration:#日志输出log-impl:org.apache.ibatis.logging.stdout.StdO......
  • MyBatis
    1.概念Mybatis是一款半ORM(对象关系映射)的持久层框架,支持定制化SQL、存储过程以及高级映射。避免了几乎所有的JDBC代码和手动设置参数及获取结果集。可以使用注解或......
  • Mybatis学习
    什么是Mybatis?看官网的定义:MyBatis是一款优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射。MyBatis免除了几乎所有的JDBC代码以及设置参数和获取结果集的......
  • Mybatis(2022-09-29)
    SSMSpringMVC+Spring+Mybatis3SpringMVC:充当的就是Servlet的角色。可以理解为SpringMVC是Spring的WEB支持。1Mybatis:充当的就是Dao层。2Spring:充当的时一个润滑油......
  • springboot+mybatis 双数据源配置
    maven依赖spring-boot-starter-webmybatis-spring-boot-startermysql-connector-javalombokapplication.ymlserver:port:8080#启动端口spring:datasource:......