调用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("批量添加成功");
    }
}
相关推荐
彭于晏Yan17 小时前
OkHttp 与 RestTemplate 技术选型对比
java·spring boot·后端·okhttp
jzlhll12317 小时前
Kotlin 协程高级用法之 NonCancellable
android·开发语言·kotlin
金銀銅鐵17 小时前
[Java] 如何理解 class 文件中字段的 descriptor?
java·后端
5008417 小时前
Graph Engine 是什么,为什么需要它
java·人工智能·性能优化·ocr·wpf
我是唐青枫17 小时前
C#.NET YARP + OpenTelemetry:网关链路追踪实战
开发语言·c#·.net
芯芯点灯17 小时前
gd32f303烧录提示Flash Timeout. Reset the Target and try it again.;
开发语言·前端·javascript
未若君雅裁17 小时前
服务雪崩、降级、熔断与服务保护
java·微服务
枫叶丹417 小时前
【HarmonyOS 6.0】Enterprise Space Kit:空间管理服务深入解析
开发语言·华为·harmonyos
就叫_这个吧17 小时前
Java实现线程间的通讯--使用synchronized关键字和JUC方式实现
java·开发语言