MyBatis-Plus--使用

原文网址:MyBatis-Plus--使用_IT利刃出鞘的博客-CSDN博客

简介

备注

        以下所有链接版本都指3.x版本。2.x版本网址:将https://mybatis.plus/改为https://mp.baomidou.com/即可。

官网

https://baomidou.com/

类型对应

Java

SQL

LocalDateTime

datetime

DateTimedatetime
Datedatetime
BigDecimal

decimal(a, b)

a:指定小数点左边和右边可以存储的十进制数字的最大个数,最大值:65。

b:指定小数点右边可以存储的十进制数字的最大个数。b必须是从 0 到 a之间的值。b默认是 0。

重要的类

所在路径:com\baomidou\mybatisplus\*

说明

BaseMapper.java

crud方法。(这是一个接口)

ServiceImpl.java

对BaseMapper.java的封装,实现IService接口。有:list、saveOrUpdate、count等方法。

可以直接用,或者新建类来继承此类。

IService.java

这是一个接口,一般与ServiceImpl.java结合使用,例如:产品服务:

//接口

public interface IProductService extends IService<Product>{

}

//实现

public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>

        implements IProductService{

}

此时,就可以直接调用IService的接口来使用ServiceImpl的实现方法了。

Wrappers.java

提供创建Wrapper、LambdaWrapper的静态方法。

ChainWrappers.java

提供创建ChainLambdaWrapper的静态方法。

IService.java

Iservice.java所有方法

IService.java方法说明

方法说明
getBaseMapper获得对应的baseMapper。从而可以去调用BaseMapper方法。当然,实际上IService的方法已完全包含BaseMapper的方法,无需这样做。
getOne

1个参数时,若有多个值则报错。

2个参数时,若第二个参数设为false,则有多个值时不报错,取第一个。

lambdaQuery

会返回一个LambdaQueryChainWrapper实例,用法见Wrapper专题。

本处示例:

List<User> list = userService.lambdaQuery().eq(User::getAge, 18).list();

lambdaUpdate

会返回一个LambdaUpdateChainWrapper实例,用法见Wrapper专题。可更新/删除

本处示例:

boolean update = userService.lambdaUpdate().eq(User::getAge, 18).set(User::getAge, 31).update();

boolean remove = userService.lambdaUpdate().eq(User::getAge, 18).remove();

list无参数可查询所有
saveBatch若参数为null,则返回false
saveOrUpdate通过id来判断。若存在此id则更新,没有则插入。

参数Wrapper

可以跟LambdaQueryWrapper,例如:remove(new LambdaQueryWrapper<User>().eq(User::getName, "Tony"));
不能跟LambdaQueryChainWrapper,例如:remove(lambdaQuery().eq(User::getName, "Tony")),否则报错:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error evaluating expression 'ew.entity != null'. Cause: org.apache.ibatis.ognl.OgnlException: entity [com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not use this method for "getEntity"]

返回值为list

例如:list();若一项都没有,则会返回空的List,需要用list.isEmpty()判断,只用list == null判断是不够的

BaseMapper.java

BaseMapper.java所有方法

项目实例

源码地址

https://gitee.com/shapeless/demo_MybtisPlus/tree/master/MultiTable_Page

项目结构

config

package com.example.conf;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@MapperScan("com.example.**.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

entity/vo

package com.example.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 lombok.Data;

import java.util.Date;

@Data
@TableName("t_question")
public class Question {
    // 问答主键id
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    // 学生外键id
    @TableField("student_id")
    private Integer studentId;

    // 问题内容
    private String content;

    // 问题悬赏的积分
    private Integer value;
}
package com.example.entity;

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

@Data
@TableName("t_student")
public class Student {
    // 学生主键id
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    // 学生名称
    private String name;

    // 学生积分数
    private Integer points;
}
package com.example.vo;

import lombok.Data;

import java.io.Serializable;

@Data
public class QuestionStudentVO {
    // 问答主键id
    private Integer id;

    // 学生外键id
    private Integer studentId;

    private String name;

    // 问题内容
    private String content;

    // 问题悬赏的积分
    private Integer value;
}

mapper

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Question;
import com.example.vo.QuestionStudentVO;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface QuestionMapper extends BaseMapper<Question> {
    @Select("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
    List<QuestionStudentVO> getQuestionStudent();

    @Select("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
    List<QuestionStudentVO> getQuestionStudentPage (Page<QuestionStudentVO> page);
}
package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.Student;

@Repository
public interface StudentMapper extends BaseMapper<Student> {
}

service

Question

package com.example.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.entity.Question;
import com.example.vo.QuestionStudentVO;

import java.util.List;

public interface QuestionService extends IService<Question> {
    Page<QuestionStudentVO> getQuestionStudentPage (Page<QuestionStudentVO> page);

    List<QuestionStudentVO> getQuestionStudent();
}
package com.example.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Question;
import com.example.mapper.QuestionMapper;
import com.example.service.QuestionService;
import com.example.vo.QuestionStudentVO;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    //下边的两处this.baseMapper都可以用自动注入的QuestionMapper替换
    //即:
    //@Autowired
    //private QuestionMapper questionMapper;

    @Override
    public List<QuestionStudentVO> getQuestionStudent() {
        return this.baseMapper.getQuestionStudent();
    }

    @Override
    public Page<QuestionStudentVO> getQuestionStudentPage (Page<QuestionStudentVO> page) {
        return page.setRecords(this.baseMapper.getQuestionStudentPage (page));
    }
}

 Student

package com.example.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.entity.Student;

public interface StudentService extends IService<Student> {
    public Student getRandomStudent();

    public int getCountOfStudents();
}
package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Student;
import com.example.mapper.StudentMapper;
import com.example.service.StudentService;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    //下边的两处this.baseMapper都可以用自动注入的StudentMapper替换
    //即:
    //@Autowired
    //private StudentMapper studentMapper;

    @Override
    public Student getRandomStudent() {
        return this.baseMapper.selectOne(null);
    }

    @Override
    public int getCountOfStudents() {
        return count(null);
    }
}

controller

package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Question;
import com.example.entity.Student;
import com.example.service.QuestionService;
import com.example.service.StudentService;
import com.example.vo.QuestionStudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    QuestionService questionService;

    @Autowired
    StudentService studentService;

    @GetMapping("/getRandomStudent")
    public Student getRundomStudent() {
        Student student = studentService.getRandomStudent();
        return student;
    }

    @GetMapping("/getStudentCount")
    public Integer getmStudentCount() {
        Integer integer = studentService.getCountOfStudents();
        return integer;
    }

    @GetMapping("/getAllQuestionWithStudent")
    public Map<String, Object> getAllQuestionWithStudent() {
        Map<String, Object> map = new HashMap<>();
        List<QuestionStudentVO> questionStudent = questionService.getQuestionStudent();
        if (questionStudent.size() == 0) {
            map.put("code", 400);
        } else {
            map.put("code", 200);
            map.put("data", questionStudent);
        }
        return map;
    }

    @GetMapping("/getAllQuestionWithStudentByPage/{page}/{size}")
    public Map<String, Object> getAllQuestionWithStudentByPage(@PathVariable Integer page, @PathVariable Integer size) {
        Map<String, Object> map = new HashMap<>();
        Page<QuestionStudentVO> questionStudent = questionService.getQuestionStudentPage (new Page<>(page, size));
        if (questionStudent.getRecords().size() == 0) {
            map.put("code", 400);
        } else {
            map.put("code", 200);
            map.put("data", questionStudent);
        }
        return map;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT利刃出鞘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值