mybatis快速入门

mybatis快速入门

mybatis plus简化了mybatis开发,极大的提高了开发效率。

代码编写

实体类:

package com.example.mybatisplusdemo.entity;

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

@Data
@TableName("user")
public class User {
    private int id;
    private String name;
    private int age;
    private String email;
}

mapper接口:

package com.example.mybatisplusdemo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplusdemo.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

service类:

package com.example.mybatisplusdemo.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.mybatisplusdemo.entity.User;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;

public interface UserService extends IService<User> {

}
package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplusdemo.entity.User;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

controller类:

package com.example.mybatisplusdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.entity.User;
import com.example.mybatisplusdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public String add(@RequestBody User user){
        boolean save = userService.save(user);
        return save ? "添加成功" : "添加失败";
    }

    @GetMapping("list")
    public List<User> list(){
        return userService.list();
    }

    // 根据用户id查询用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable long id){
        User user = userService.getById(id);
        return user;
    }
    
    // 根据id更新用户信息
    @PostMapping("/update")
    public boolean updateById(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    
    
    // 根据普通条件更新用户信息
    // 或者创建一个VO对象用来接受前端传过来的信息
    @PostMapping("condition")
    public boolean updateByCondition(@RequestBody Map<String, Object> map){
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getEmail, map.get("emailWhere"));
        wrapper.set(User::getAge, map.get("age"));
        wrapper.set(User::getName, map.get("name"));
        wrapper.set(User::getEmail, map.get("email"));

        return userService.update(wrapper);
    }
    

    @DeleteMapping("/{id}")
    public boolean deleteById(@PathVariable long id){
        boolean flag = userService.removeById(id);
        return flag;
    }

     // 分页查询用户
    @GetMapping("/page")
    public Page<User> getUserPage(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size) {
        // 创建查询条件,这里不设置条件表示查询所有记录
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 创建分页对象,current 表示当前页码,size 表示每页记录数
        Page<User> page = new Page<>(current, size);
        return userService.page(page, queryWrapper);
    }

    // 条件查询用户
    @GetMapping("/query")
    public List<User> queryUsers(@RequestParam String name, @RequestParam int age) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name).eq("age", age);
        return userService.list(wrapper);
    }

}

启动类:

package com.example.mybatisplusdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@MapperScan
public class MybatisplusdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisplusdemoApplication.class, args);
    }

}

数据库脚本:

-- mytest.`user` definition

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',13,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',14,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',15,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',16,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',17,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',18,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',19,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',20,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',21,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',22,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',23,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',24,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',25,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',26,'110100@qq.com');
INSERT INTO mytest.`user` (name,age,email) VALUES ('doudou',27,'110100@qq.com');

执行情况

添加用户:

image

查询所有用户:

image

通过id查询用户:

image

通过id删除用户:

image

根据条件查询用户:

image

分页查询:

添加配置类:

package com.example.mybatisplusdemo.configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
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 mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

image

{
    "records": [
        {
            "id": 14,
            "name": "doudou",
            "age": 21,
            "email": "110100@qq.com"
        },
        {
            "id": 15,
            "name": "doudou",
            "age": 22,
            "email": "110100@qq.com"
        },
        {
            "id": 16,
            "name": "doudou",
            "age": 23,
            "email": "110100@qq.com"
        },
        {
            "id": 17,
            "name": "doudou",
            "age": 24,
            "email": "110100@qq.com"
        },
        {
            "id": 18,
            "name": "doudou",
            "age": 25,
            "email": "110100@qq.com"
        },
        {
            "id": 19,
            "name": "doudou",
            "age": 26,
            "email": "110100@qq.com"
        },
        {
            "id": 20,
            "name": "doudou",
            "age": 27,
            "email": "110100@qq.com"
        }
    ],
    "total": 17,
    "size": 10,
    "current": 2,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 2
}
==>  Preparing: SELECT id,name,age,email FROM user LIMIT ?,?
==> Parameters: 10(Long), 10(Long)
<==    Columns: id, name, age, email
<==        Row: 14, doudou, 21, 110100@qq.com
<==        Row: 15, doudou, 22, 110100@qq.com
<==        Row: 16, doudou, 23, 110100@qq.com
<==        Row: 17, doudou, 24, 110100@qq.com
<==        Row: 18, doudou, 25, 110100@qq.com
<==        Row: 19, doudou, 26, 110100@qq.com
<==        Row: 20, doudou, 27, 110100@qq.com
<==      Total: 7

根据id更新用户信息:

image

根据普通条件更新用户信息:

image

实际使用过程中遇到的问题

如果在启动类上加上@MapperScan注解的话,会报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.mybatisplusdemo.service.UserService.getBaseMapper

所以要将@MapperScan注解去掉。

如果测试过程中返回400的错误表示,请求方式不对,比如应该使用post请求,结果你使用的是get请求。

posted on   ~码铃薯~  阅读(2)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 分享4款.NET开源、免费、实用的商城系统
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
历史上的今天:
2021-01-30 集合总结
2021-01-30 Collections工具类的使用
2021-01-30 HashMap底层源码分析(底部含给面试官讲HashMap话术)
2021-01-30 Map接口之TreeMap
2021-01-30 Map接口之HashMap
2021-01-30 Set接口之TreeSet
2021-01-30 ***\*Set子接口\**** 之***\*HashSet\****

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示