调用Service层操作数据

参考视频:MyBatisPlus教程,一套玩转mybatisplus框架,mybatis-plus轻松上手 点击观看

文章目录

  • [- 创建UserService并继承IService](#- 创建UserService并继承IService)
  • [- 创建UserService的实现类并继承ServiceImpl](#- 创建UserService的实现类并继承ServiceImpl)
  • [- 操作数据](#- 操作数据)

MyBatisPlus中有一个接口IService和其实现类ServiceImpl,封装了常见的业务层逻辑。因此在使用的时候仅需在自己定义的Service接口中继承IService接口,在自己的实现类中实现自己的Service并继承ServiceImpl即可。

- 创建UserService并继承IService

java 复制代码
package com.findx.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.findx.mybatisplus.pojo.User;

public interface UserService extends IService<User> {
}

- 创建UserService的实现类并继承ServiceImpl

java 复制代码
package com.findx.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.findx.mybatisplus.mapper.UserMapper;
import com.findx.mybatisplus.service.UserService;
import com.findx.mybatisplus.pojo.User;
import org.springframework.stereotype.Service;

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

- 操作数据

java 复制代码
package com.findx.mybatisplus;

import com.findx.mybatisplus.pojo.User;
import com.findx.mybatisplus.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MybatisPlusServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testGetCount(){
        long count = userService.count();
        System.out.println("总记录数:" + count);
    }
    @Test
    //批量添加
    public void testInsertMore(){
        User user1 = new User();
        user1.setName("张叔");
        user1.setAge(32);
        User user2 = new User();
        user2.setName("李四");
        user2.setAge(18);
        userService.saveBatch(java.util.Arrays.asList(user1, user2));
        System.out.println("批量添加成功");
    }
}
相关推荐
asdzx672 小时前
使用 Python 读取 PDF: 提取文本和图片
开发语言·python·pdf
沐知全栈开发2 小时前
jQuery Mobile 表单选择
开发语言
MoonBit月兔2 小时前
MoonBit 大型软件合成挑战赛决赛暨 Meetup 0.9 版本专场回顾
大数据·开发语言·人工智能·moonbit
宣宣猪的小花园.2 小时前
C语言重难点全解析:指针到内存四区
c语言·开发语言
南宫萧幕2 小时前
HEV 智能能量管理实战:从 MPC/PPO 理论解析到 Python-Simulink 联合仿真闭环全流程
开发语言·python·算法·matlab·控制
码农的神经元2 小时前
Python 实现县域变电站智能巡检与抢修调度:地图、路径规划与恢复策略
开发语言·python
user_admin_god2 小时前
SSE 流式响应 Chunk 被截断问题的排查与修复
java·人工智能·spring boot·spring·maven·mybatis
我命由我123452 小时前
Java 开发 - CountDownLatch 不需要手动关闭
android·java·开发语言·jvm·kotlin·android studio·android-studio
小研说技术2 小时前
结构化输出让Agent返回可预测的格式数据
java·人工智能