调用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("批量添加成功");
    }
}
相关推荐
c++之路3 小时前
CMake 系列教程(二):基础命令详解
开发语言·c++
阿维的博客日记5 小时前
Hippo4j 线程池监控平台部署手册
java·spring boot·后端
南境十里·墨染春水7 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
C+++Python7 小时前
详细介绍一下Java泛型的通配符
java·windows·python
JosieBook8 小时前
【数据库】时序预测能力的分级进化:TimechoAI如何让每一类用户都能精准预见未来
java·开发语言·数据库
加号38 小时前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
diving deep9 小时前
脚本速览-python
开发语言·python
一生了无挂9 小时前
Java处理JSON技巧教学(从基础到高阶实战全覆盖)
java·开发语言·json
李白的天不白9 小时前
使用 SmartAdmin 进行前后端开发
java·前端
swordbob9 小时前
Spring 单例 Bean 是线程安全的吗?
java·开发语言