MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window) 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发(一般不需要写mapper.xml)、提高效率而生。
通过springboot快速部署并使用mybatis-Plus
1.创建一个springboot项目
编辑组名和java版本
选择必要依赖
设置项目名与路径
由于之前没有mybatis-plus依赖,故上maven镜像仓库中找到相应的依赖添加到项目的pom.xml文件中并刷新maven。
2.创建一个用于操作数据的pg数据库(mysql同理)
我这里创建的是一个名为school的数据库,主要针对book表进行查询,大致内容如下:
3.配置数据库信息与mybatis-plus依赖
配置数据库的加载驱动,url,用户名与密码并设置mybatis-plus配置打印日志到控制台。
application.yml的配置文件内容如下:
spring
datasource
driver-class-name org.postgresql.Driver
url jdbc postgresql //localhost 5432/school
username postgres
password123456
mybatis-plus
configuration
log-impl org.apache.ibatis.logging.stdout.StdOutImpl
4.编写实体层中的实体类Book,添加相应注解
5.编写持久层中的mapper接口
在接口上添加@Repository注解并继承mybatis-plus的mapper接口BaseMapper<T>
对于简单的增删改查直接调用该接口中的方法即可,具体方法参见官网,如果有复杂的方法,通过相应注解@Select("sql"),@Insert("sql"),@Delete("sql"),@Update("sql")编写sql并添加相应的方法声明
在springboot启动类添加扫描器
6.编写业务层的业务接口与实现类完成对数据的增删改查
接口
接口实现类:
package com.shen.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shen.dao.HandleBookDao;
import com.shen.entity.Book;
import com.shen.service.HandleBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class HandleBookServiceImpl implements HandleBookService {
HandleBookDao handleBookDao;
//添加图书
public Integer addBook(Book book) {
return handleBookDao.insert(book);
}
//删除图书
public Integer deleteBook(String name) {
QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name",name);
return handleBookDao.delete(queryWrapper);
}
// 修改图书
public Integer updateBook(Integer id, Double price) {
UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id",id)
.set("price",price);
return handleBookDao.update(null,updateWrapper);
}
//查询图书
public List<Book> selectBook() {
return handleBookDao.selectList(null);
}
}
7.编写控制层的方法,主要是对业务层的调用。
package com.shen.controller;
import com.shen.entity.Book;
import com.shen.service.HandleBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
("api/vi/test")
public class TestController {
HandleBookService handleBookService;
//@RequestBody将请求信息的body内容绑定到程序的实体类中,此注解必须加不然接受不到数据
("/addBook")
public Integer addBook( Book book){
System.out.println(book);
return handleBookService.addBook(book);
}
("/deleteBook")
public Integer deleteBook(String name){
System.out.println(name);
return handleBookService.deleteBook(name);
}
("/updateBook")
public Integer updateBook(Integer id,Double price){
System.out.println(id);
return handleBookService.updateBook(id,price);
}
("/selectBook")
public List<Book> selectBook(){
return handleBookService.selectBook();
}
}
8.通过postman来测试
对数据的增删改查进行测试