mysql plus crud_使用 Mybatis-plus 进行 crud 操作

1 Mybatis-Plus简介

1.1 什么是Mybatis-Plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

1.2 为什么要学习Mybatis-Plus

我们已经学习过Mybatis这个框架,我们只需要在dao层定义抽象接口,基于Mybatis零实现的特性,就可以实现对数据库的crud操作。在业务类型比较多的时候,我们需要重复的定义一堆功能类似的接口方法。

使用Mybatis-plus工具,我们只需要将我们定义的抽象接口,继承一个公用的 BaseMapper 接口,就可以获得一组通用的crud方法,来操作数据库。使用Mybatis-plus时,甚至都不需要任何的xml映射文件或者接口方法注解,真正的dao层零实现。

2 入门示例

2.1 需求

使用Mybatis-Plus实现对用户的crud操作。

2.2 配置步骤说明

搭建环境(创建项目、导入包)

配置Mybaits-Plus(基于Spring实现)

编写测试代码

2.3 配置步骤

2.3.1 第一步:搭建环境

2.3.1.1 数据库准备

CREATE TABLE `tb_user` (

`id` bigint(20) NOT NULL COMMENT '主键ID',

`name` varchar(30) DEFAULT NULL COMMENT '姓名',

`age` int(11) DEFAULT NULL COMMENT '年龄',

`email` varchar(50) DEFAULT NULL COMMENT '邮箱',

PRIMARY KEY (`id`)

)

2.3.1.2 说明

Mybatis-Plus并没有提供单独的jar包,而是通过Maven(或者gradle)来管理jar依赖。

Mybatis-Plus是基于Spring框架实现的,因此使用Mybatis-Plus,必须导入Spring相关依赖。

2.3.1.3 添加依赖

编写 pom 配置文件

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">

4.0.0

org.oza.mybatisplus

mybatisplus-demo-start

1.0-SNAPSHOT

com.baomidou

mybatis-plus

3.1.2

org.springframework

spring-context

4.3.2.RELEASE

org.springframework

spring-jdbc

4.3.2.RELEASE

org.springframework

spring-test

4.3.2.RELEASE

mysql

mysql-connector-java

8.0.16

com.alibaba

druid

1.1.9

junit

junit

4.12

2.3.2 第二步:创建User实体类

使用Mybatis-Plus可以不使用xml文件,而是基于一组注解来解决实体类和数据库表的映射问题。以下注解作用于实体类的字段声明上:

注解

含义

@TableName(value="tb_user")

指定对应的表,表名和类名一致时,可以省略value属性。

@TableId

指定表的主键。Value属性指定表的主键字段,和属性名一致时,可以省略。Type指定主键的增长策略。

@TableField

指定类的属性映射的表字段,名称一致时可以省略该注解。

源码如下:

package org.oza.mybatisplus.pojo;

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("tb_user")

public class User {

@TableId(value = "u_id", type = IdType.AUTO)

private Long id;

@TableField("u_name")

private String name;

@TableField("u_age")

private Integer age;

@TableField("u_email")

private String email;

}

2.3.3 第三步:创建UserMapper接口

只需要继承BaseMapper公共接口即可。

package org.oza.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import org.apache.ibatis.annotations.Result;

import org.apache.ibatis.annotations.Results;

import org.apache.ibatis.annotations.Select;

import org.oza.mybatisplus.pojo.User;

import java.util.List;

public interface UserMapper extends BaseMapper {

/**

* 自定义方法,展示所有用户的用户名

* @return 用户名集合

*/

@Select("select u_name from tb_user")

List listAllUsername();

/**

* 自定义方法,搜索所有用户的邮箱,并封装进 user 对象里

* @return

*/

@Select("select u_email from tb_user")

@Results(

@Result(column = "u_email", property = "email")

)

List listAllEmail();

}

2.3.4 第四步:配置 spring 配置文件

xmlns:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd">

2.3.5 第五步:编写测试代码

package org.oza.mybatisplus;

import com.baomidou.mybatisplus.core.conditions.Wrapper;

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 org.apache.ibatis.session.RowBounds;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.oza.mybatisplus.mapper.UserMapper;

import org.oza.mybatisplus.pojo.User;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.TestExecutionListeners;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.SQLOutput;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration("classpath:spring-mybatisplus.xml")

public class CrudTest {

@Autowired

private UserMapper userMapper;

/**

* 插入一条数据

*/

@Test

public void insert() {

User user = new User(null, "张无忌", 18, "zwj@qq.com");

int insert = userMapper.insert(user);

System.out.println("Affected rows: " + insert);

}

/**

* 根据 ID 删除

*/

@Test

public void deleteById(){

int delete = userMapper.deleteById(1);

System.out.println("Affected rows: " + delete);

}

/**

* 根据 ID 查询

*/

@Test

public void selectById() {

User user = userMapper.selectById(1);

System.out.println(user);

}

/**

* 根据条件删除, 删除名字含 张 字的

*/

@Test

public void deleteByCondition(){

QueryWrapper userWrapper = new QueryWrapper<>();

userWrapper.like("u_name", "张");

int delete = userMapper.delete(userWrapper);

System.out.println("Affected rows: " + delete);

}

/**

* 根据 Id 进行修改,只修改不为空的数据

*/

@Test

public void update() {

User user = new User(4L, null, 25, null);

int update = userMapper.updateById(user);

System.out.println("Affected rows: " + update);

}

/**

* 批量修改,将所有名字含有 张 的都修改

*/

@Test

public void updateByCondition() {

User user = new User(null, null, 25, null);

UpdateWrapper updateWrapper = new UpdateWrapper<>();

updateWrapper.like("u_name", "张");

int update = userMapper.update(user, updateWrapper);

System.out.println("Affected rows: " + update);

}

/**

* 根据条件查询,将所有名字带 张 的查出来

*/

@Test

public void selectByCondition() {

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper.like("u_name", "张");

List users = userMapper.selectList(queryWrapper);

users.forEach(user -> System.out.println(user));

}

/**

* 分页查询,selectPage 可以传入两个参数

* 参数 1:Page 对象,包含了分页信息,其构造方法参数

* 参数 1:当前页,从 1 开始

* 参数 2:页面容量

* 参数 2:QueryWrapper 对象,设置搜索的条件

* 结果:IPage 抽象类的子类对象,包含了一下信息:

* 1. 当前页

* 2. 总页数

* 3. 总记录数

* 4. 页面容量

* 5. 当前页的记录

*/

@Test

public void selectByPage() {

IPage iPage = userMapper.selectPage(new Page(1L, 2), null);

System.out.println("current page: " + iPage.getCurrent());

System.out.println("total pages: " + iPage.getPages());

System.out.println("total records: " + iPage.getTotal());

System.out.println("page size: " + iPage.getSize());

System.out.println("records: " + iPage.getRecords());

}

/**

* 自定义方法测试

*/

@Test

public void listAllUsername() {

List usernames = userMapper.listAllUsername();

System.out.println(usernames);

List users = userMapper.listAllEmail();

users.forEach(user -> System.out.println(user.getEmail()));

}

}

2.3.6 第六步:编写 Service 层

mybatis-plus 还提供了 Service 层的快速实现。同样不需要写任何实现方法,即可轻松构建 Service 层。

需要注意的是,service 层方法名和 dao 层的方法名有些许不同

编写 UserService 接口

package org.oza.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;

import org.oza.mybatisplus.pojo.User;

/**

* 继承 IService,泛型中写入 pojo 类

*/

public interface UserService extends IService {

}

编写 UserServiceImpl 实现类

package org.oza.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.oza.mybatisplus.mapper.UserMapper;

import org.oza.mybatisplus.pojo.User;

import org.oza.mybatisplus.service.UserService;

import org.springframework.stereotype.Service;

/**

* 继承 ServiceImpl,实现 UserService 接口

* ServiceImpl:该类实现了 IService 接口,需要两个泛型参数

* 参数1:对应的 Mapper 类

* 参数2:对应的 Pojo 类

*/

@Service

public class UserServiceImpl extends ServiceImpl implements UserService {

}

测试代码

/**

* 使用 service 层执行分页查询

*/

@Test

public void serviceTest() {

IPage iPage = userService.page(new Page(1L, 2), null);

System.out.println("current page: " + iPage.getCurrent());

System.out.println("total pages: " + iPage.getPages());

System.out.println("total records: " + iPage.getTotal());

System.out.println("page size: " + iPage.getSize());

System.out.println("records: " + iPage.getRecords());

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值