Mybatis-Plus学习记录
项目结构
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.LimiChan</groupId>
<artifactId>MybatisPlusStudy</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
<!-- mybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Mysql数据库表
application.yml
server:
port: 8080
servlet:
context-path: /
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatisPlueStudy?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
username: root
password: 123456
mybatis-plus:
mapper-locations: classpath:/mappers/**.xml
# 如果是放在src/main/java目录下 classpath:/com/*/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/**.xml
MybatisplusStudyApplication
package com.limichan.mybatisplus_study;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.limichan.mybatisplus_study.dao")
public class MybatisplusStudyApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusStudyApplication.class, args);
}
}
dao
package com.limichan.mybatisplus_study.dao;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.limichan.mybatisplus_study.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 可以直接调用已经封装好的方法,类似于JPA
public interface UserDao extends BaseMapper<User> {
// 自定义sql语句
// 方法1:
@Select("SELECT * FROM user where name = #{name}")
User selectByName(@Param("name") String name);
// 方法2: 使用xml文件
List<User> selectByMyWrapper(@Param(Constants.WRAPPER) Wrapper<User> userWrapper);
}
entity
package com.limichan.mybatisplus_study.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* user
* @author
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "user")
public class User{
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 邮箱
*/
private String email;
}
service + serviceImpl
package com.limichan.mybatisplus_study.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.limichan.mybatisplus_study.entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserService {
public List<User> findAll();
// 根据 entity 条件,查询一条记录
// T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 插入
public Integer insert(User user);
// 删除主键值在integerList的行
public Integer deleteBatchIds(List<Integer> integerList);
// 通过主键删除
public Integer deleteById(Integer id);
// 通过id更改
public Integer updateById(User user);
// 根据id查询
public User selectById(Integer id);
// 根据姓名查询
public User selectByName(String name);
// 通过Lambda表达式
List<User> selectByMyWrapper(@Param(Constants.WRAPPER) Wrapper<User> userWrapper);
// 分页查询
List<User> selectUsersForPage(Page page);
}
package com.limichan.mybatisplus_study.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.limichan.mybatisplus_study.dao.UserDao;
import com.limichan.mybatisplus_study.entity.User;
import com.limichan.mybatisplus_study.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("UserService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public List<User> findAll() {
return userDao.selectList(null);
}
@Override
public Integer insert(User user) {
return userDao.insert(user);
}
@Override
public Integer deleteBatchIds(List<Integer> integerList) {
return userDao.deleteBatchIds(integerList);
}
@Override
public Integer deleteById(Integer id) {
return userDao.deleteById(id);
}
@Override
public Integer updateById(User user) {
return userDao.updateById(user);
}
@Override
public User selectById(Integer id) {
return userDao.selectById(id);
}
@Override
public User selectByName(String name) {
return userDao.selectByName(name);
}
@Override
public List<User> selectByMyWrapper(Wrapper<User> userWrapper) {
return userDao.selectByMyWrapper(userWrapper);
}
@Override
public List<User> selectUsersForPage(Page page) {
IPage<User> userIPage = page;
userIPage = userDao.selectPage(userIPage,null);
return userIPage.getRecords();
// 自定义分页查询
// QueryWrapper<User> query = Wrappers.query();
// query.gt("age", 5);
// Page<User> page1 = new Page<>(1, 2);
// IPage<User> userIPage1 = userDao.selectPage(page1,query);
IPage<Map<String, Object>> userIPage = userMapper.selectUserPage(page, query);
// System.out.println("总记录数:"+userIPage1.getTotal());
// System.out.println("总页数:"+userIPage1.getPages());
// List<User> users = userIPage.getRecords();
List<Map<String, Object>> users = userIPage.getRecords();
// users.forEach(System.out::println);
}
}
controller
package com.limichan.mybatisplus_study.controller;
import com.limichan.mybatisplus_study.entity.User;
import com.limichan.mybatisplus_study.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class UserController {
@Resource
private UserService userService;
@GetMapping("/userinfo")
@ResponseBody
public List<User> getUser(){
return userService.findAll();
}
}
config
package com.limichan.mybatisplus_study.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 分页查询配置类!很重要,不然分页查询无效,总是返回全部数据
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
Test
package com.limichan.mybatisplus_study.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.limichan.mybatisplus_study.dao.UserDao;
import com.limichan.mybatisplus_study.entity.User;
import com.limichan.mybatisplus_study.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
// 测试最好用Junit4, j5不太好用- -
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void findAll() {
List<User> userList = userService.findAll();
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void insert() {
User user = new User();
// alter table user change id id int auto_increment; 需要先将id设置成自动增长
user.setName("雷步云");
user.setAge(15);
user.setEmail("508222866@qq.com");
userService.insert(user);
System.out.println("insert成功!" + "查看所有行:");
findAll();
}
@Test
public void deleteBatchIds() {
List<Integer> integerList = new ArrayList<>();
integerList.add(3);
integerList.add(4);
integerList.add(5);
userService.deleteBatchIds(integerList);
System.out.println("deleteBatchIds成功!" + "查看所有行");
findAll();
}
@Test
public void deleteById() {
// 如果删除不存在的行,仍然可以正常运行
userService.deleteById(7);
System.out.println("delete成功!" + "查看所有行");
findAll();
}
@Test
public void updateById() {
User newUser = new User(6L, null, 19, null);
userService.updateById(newUser);
System.out.println("update成功" + "查看所有行");
findAll();
}
@Test
public void selectById() {
// 如果未查询到则为null,成功则返回对象
System.out.println(userService.selectById(3));
}
// 测试自定义sql语句的方法
@Test
public void selectByName() {
String name = "雷步云";
System.out.println(userService.selectByName(name));
}
@Test
public void selectByWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper();
// 查找所有姓名 != "雷步云" 的User
wrapper.ne("name", "雷步云");
List<User> users = userService.selectByMyWrapper(wrapper);
users.forEach(System.out::println);
}
// 测试分页查询
@Test
public void selectUsersForPage() {
// Page构造函数的两个参数分别为,查询的页数(1开始)以及每页的行数
List<User> userList = userService.selectUsersForPage(new Page(2, 2));
userList.forEach(System.out::println);
}
}
注意点
一。复制的时候需要修改的地方
①pom.xml中项目名称之类的跟着变
②application.yml中数据库的账号密码,数据库设置为你自己的
二。不懂的多查阅官方的文档 : 点击我