目录
一、MybatisPlus快速入门
1、知识轰炸
2、实操演练
(1)新建项目
(2)添加依赖
(3)添加配置
(4)添加映射层
(5)启动类中添加注解
(6)创建控制层
(7)添加控制类
(8)创建UserMapper接口
(9)创建用户实体类
(10)继续编写UserMapper接口
(10)在UserController类中实现UserMapper接口中的find方法
(11)修改返回值类型
(12)实现插入功能
(13)发现问题,解决问题
(14)使用MybatisPlus简化语法
查询:
插入:
删除:
修改:
二、多表查询及分页查询
1、知识轰炸
2、实操演练
多表查询
(1)建立关联表
表一:t_user
表二:t_order
(2)创建Order类
(3)修改User类
(4)创建UserMapper映射
(5)创建OrderMapper映射
条件查询
条件构造器 | MyBatis-Plus
分页查询
com.baomidou
mybatis-plus-boot-starter
3.4.2
mysql
mysql-connector-java
5.1.47
com.alibaba
druid-spring-boot-starter
1.1.20
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
(注意:数据库、账号、密码改成自己的)
mapper包右键copy path 选最后一项复制路径,添加到mapperscan中
package com.example.bilibili_demo02.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/user")
public String query(){
return "查询用户";
}
}
package com.example.bilibili_demo02.mapper;
public interface UserMapper {
//public List<>
}
发现需要查询用户信息,将全部信息放入集合中。所以需要用户的实体类,立刻去创建。
package com.example.bilibili_demo02.entity;
public class User {
private int id;
private String username;
private String password;
private String birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday() {
return birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday='" + birthday + '\'' +
'}';
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
package com.example.bilibili_demo02_1.mapper;
import com.example.bilibili_demo02_1.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user")//后面不加分号
public List find();
}
package com.example.bilibili_demo02_1.controller;
import com.example.bilibili_demo02_1.entity.User;
import com.example.bilibili_demo02_1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;// @Autowired自动注入属性
@GetMapping("/user")
public String query(){
List list = userMapper.find();
System.out.println(list);
return "查询用户";
}
}
运行程序看看效果:
http://localhost:8080/user
由于前后端分离项目中数据是json格式传递的,那么我们从数据库返回的数据类型就应该是List。List中的数据会自动转换成json格式数据传递到前端,这样前端拿到json格式的数据就方便展示了。
UserController类
package com.example.bilibili_demo02_1.controller;
import com.example.bilibili_demo02_1.entity.User;
import com.example.bilibili_demo02_1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;// @Autowired自动注入属性
@GetMapping("/user")
public List query(){
List list = userMapper.find();
System.out.println(list);
return list;
}
}
看看效果:
http://localhost:8080/user
在UserMapper接口添加插入语句
@Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
public int insert(User user);//插入成功返回1,失败返回0
UserController类中新增post请求
@PostMapping("/user")
public String save(User user){
int i = userMapper.insert(user);
if (i>0){
return "插入成功!";
}else {
return "插入失败!";
}
}
在apipost中进行插入测试
数据库中插入成功,因为没有给id赋值,所以默认为0。
同样,再次不给id赋值插入数据会发生报错,因为id是主键,主键不能有相同值,为解决这个问题,我们在设计表时,给id字段加入自增条件即可。
在UserMapper接口中继承BaseMapper
package com.example.bilibili_demo02_1.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.bilibili_demo02_1.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper {
//@Select("select * from user")//后面不加分号
//public List find();
//@Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
//public int insert(User user);//插入成功返回1,失败返回0
}
继承BaseMapper后,传入User表,就可以直接使用BaseMapper类中写好的方法就行crud操作了。
(BaseMapper中的方法如下:)
在UserController类中将find方法改为BaseMapper类自带的selectList方法
@GetMapping("/user")
public List query(){
List list = userMapper.selectList(null);
System.out.println(list);
return list;
}
效果相同。
@PostMapping("/user")
public String save(User user){
int i = userMapper.insert(user);
if (i>0){
return "插入成功!";
}else {
return "插入失败!";
}
}
@PostMapping ("/user/del")
public String remove(int id){
userMapper.deleteById(id);
return "删除成功!";
}
@PostMapping("/user/upd")
public String update(User user){
userMapper.updateById(user);
return "修改成功!";
}
@TableName,当表名与实体类名称不一致时,可以使用@TableName注解进行关联。 @TableField,当表中字段名称与实体类属性不一致时,使用@TableField进行关联 @TableId,用于标记表中的主键字段,MybatisPlus也提供了主键生成策略
更多MyBatisPlus功能请到官网查阅:简介 | MyBatis-Plus
MyBatisPlus对单表的查询做了增强,但是多表查询没有,多表查询需要用到的是Mybatis内容。
表名和类名不对应需要加注解,在Order中添加一个不存在的字段User,用来进行数据库的映射。并添加对应的toString方法
package com.example.bilibili_demo02_1.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@TableName("t_order")
public class Order
{
@TableId(type = IdType.AUTO)//获取自增id值
private int id;
//@DateTimeFormat(pattern="yyyy-MM-dd")
//@TableField("ordertime")//表中的字段名字不一致使用该注解进行绑定
//@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
private String ordertime;//springboot实体类列不能输入大写字母
private int total;
private int uid;
@TableField(exist = false)//表中不存在该属性,加注释
private User user;//一个订单对应一个用户,在订单类中创建一个user属性
@Override
public String toString() {
return "Order{" +
"id=" + id +
", ordertime='" + ordertime + '\'' +
", total=" + total +
", uid=" + uid +
", user=" + user +
'}';
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrderTime() {
return ordertime;
}
public void setOrderTime(String orderTime) {
this.ordertime = orderTime;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
}
表名和类名不对应需要加注解,在User中添加一个不存在的字段Order,用来进行数据库的映射。并添加对应的toString方法
package com.example.bilibili_demo02_1.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.List;
//如果类名和表名不一致,那么为了使用MybatisPlus减少工作量
//这里可以使用注释,将User类名与数据库表名进行绑定
//@TableName("表名")
//根据这个注释MybatisPlus会自动找到这张表
@TableName("t_user")
public class User {
@TableId(type = IdType.AUTO)//获取自增id值
private int id;
private String username;
private String password;
private String birthday;
//描述用户所有订单
@TableField(exist = false)//告诉MybatisPlus orders字段在数据库中是不存在的,避免使用BaseMapper时出现错误
private List orders;
//在User中添加一个不存在的字段,用来进行数据库的映射。并添加对应的toString方法
public List getOrders() {
return orders;
}
public void setOrders(List orders) {
this.orders = orders;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday() {
return birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday='" + birthday + '\'' +
", orders=" + orders +
'}';
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
package com.example.bilibili_demo02_1.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.bilibili_demo02_1.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper {//User是类名同时也是数据库的表名,在没有特殊注释下二者必须保持一致
@Select("select * from t_user where id =#{id}")
User selectById(int id);
//查询用户所有订单
@Select("select * from t_user")//此数查询表名用的t_user,所以User类中的注解就失效了@TableName("t_user")
@Results( {
@Result(column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password"),
@Result(column = "birthday", property = "birthday"),
@Result(column = "id", property = "orders", javaType = List.class,
many = @Many(select = "com.example.bilibili_demo02_1.mapper.OrderMapper.selectById")//将id传递给selectById(id)
//全路径copy path
//一个用户有多个订单,用many注解
),
})
List selectAllOrdersAndUser();
}
在Controller编写方法查询用户和订单(一对多)
@GetMapping("user/findAll")
public List find(){
return userMapper.selectAllOrdersAndUser();
}
package com.example.bilibili_demo02_1.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.bilibili_demo02_1.entity.Order;
import com.example.bilibili_demo02_1.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface OrderMapper extends BaseMapper {
@Select("select * from t_order where uid = #{uid}")
List selectByUid(int uid);
//查询所有订单,同时查询订单的用户
@Select("select * from t_order")
@Results({//@Results的基本用法。当数据库字段名与实体类对应的属性名不一致时,
// 可以使用@Results映射来将其对应起来。column为数据库字段名,
// porperty为实体类属性名,jdbcType为数据库字段数据类型,id为是否为主键。
@Result(column = "id",property="id"),
@Result(column = "ordertime",property="ordertime"),
@Result(column = "total",property="total"),
@Result(column = "uid",property="user",javaType = User.class,
one = @One(select = "com.example.bilibili_demo02_1.mapper.UserMapper.selectById")
),
})
List selectOneOrdersAndUser();//这个方法不在OrderController实现,要在UserMapper中实现
}
在控制层创建OrderController编写方法,查询用户和订单(一对一)
package com.example.bilibili_demo02_1.controller;
import com.example.bilibili_demo02_1.entity.Order;
import com.example.bilibili_demo02_1.entity.User;
import com.example.bilibili_demo02_1.mapper.OrderMapper;
import com.example.bilibili_demo02_1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class OrderController {
@Autowired
private OrderMapper orderMapper;// @Autowired自动注入属性
@GetMapping("/order")
public List query(){
List list = orderMapper.selectList(null);
System.out.println(list);
return list;
}
@GetMapping("/order/findAll")
public List findAll(){
List orders = orderMapper.selectOneOrdersAndUser();
return orders;
}
}
MybatisPlus条件查询
使用MybatisPlus的语法糖通过条件构造器进行符合条件的查询
在UserController创建以下代码进行测试
//条件查询
@GetMapping("/user/find")
public List findByCond(){
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("username","111");
return userMapper.selectList(queryWrapper);//条件查询
}
http://localhost:8080/user/find
单表查询使用MybatisPlus非常便捷,多表查询使用sql或者consults注解。
在user表中多添加一些数据
定义分页查询的配置类
package com.example.bilibili_demo02_1.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor paginationInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);//选择数据库类型
mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
return mybatisPlusInterceptor;
}
}
在UserController中编写分页测试代码
起始页0,每页两条数据
//分页查询
@GetMapping("/user/findBypage")
public IPage findByPage(){
//设置其实值及每页条数
Page page = new Page<>(0,2);
IPage iPage = userMapper.selectPage(page,null);//分页查询,查询条件为null
return iPage;
}
起始页0,每页两条数据
参考:Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.