调用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("批量添加成功");
    }
}
相关推荐
小羊没烦恼!4 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
俊昭喜喜里4 天前
java中的继承和多态的区别
java
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕4 天前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码4 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖4 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
此时不提桶,更待何时4 天前
01-06-A-JVM排查实战详解
java·jvm
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
vipxieliang4 天前
ValidX 在 DDD 领域驱动设计中的实践
java·spring boot
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++