IService接口和ServiceImpl实现类(Mybatis-Plus对service层的封装)

文章详细介绍了Java中的IService接口及其在Service层中的作用,用于封装CRUD操作。内容包括新增(单条与批量)、查询(单行与多行)、删除(按ID与条件)、修改(单条与批量)以及分页查询的方法。同时,文章提到了Mybatis-plus的分页实现,以及在Spring和SpringBoot中配置分页插件的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java知识点总结:想看的可以从这里进入

3.2、IService接口

BaseMapper 是用在Mapper中,而IService是在Service层使用的封装接口,它进一步封装 CRUD 。为了和BaseMapper 中方法进行区分,它采用了不同的前缀:

  1. get 查询单行
  2. remove 删除
  3. list 查询集合
  4. page 分页
  5. save新增
  6. update修改

IService还有一个实现的类ServiceImpl,在使用使用时分别对应service接口和impl实现类。

public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
3.2.1、新增
image-20230306112657281
  1. 新增一条记录

    @Resource
    private UserService userService;
    @Test
    public void testServcie(){
        User user  = new User();
        user.setUsername("service增加");
        user.setPassword("12321");
        boolean save = userService.save(user);
        System.out.println("是否成功:"+save);
    }
    
    image-20230306113912564
  2. 批量操作

    @Resource
    private UserService userService;
    @Test
    public void testServcie(){
        List<User> users = new ArrayList<>();
        User user1 = new User("批量增加1","123");
        users.add(user1);
        User user2 = new User("批量增加2","123");
        users.add(user2);
        User user3 = new User("批量增加3","123");
        users.add(user3);
        User user4 = new User("批量增加4","123");
        users.add(user4);
        User user5 = new User("批量增加5","123");
        users.add(user5);
    
        boolean save = userService.saveBatch(users);
        System.out.println("是否成功:"+save);
    }
    
    image-20230306114731705
  3. 设置批次数量

    public void testServcie(){
        List<User> users = new ArrayList<>();
        User user1 = new User("指定数量批量增加6","123");
        users.add(user1);
        User user2 = new User("指定数量批量增加7","123");
        users.add(user2);
        User user3 = new User("指定数量批量增加8","123");
        users.add(user3);
        User user4 = new User("指定数量批量增加9","123");
        users.add(user4);
        User user5 = new User("指定数量批量增加10","123");
        users.add(user5);
    
        boolean save = userService.saveBatch(users,2);
        System.out.println("是否成功:"+save);
    }
    

    image-20230306114954565

3.2.2、查询
1、单行查询

image-20230306123815377

  1. 根据id查询

    @Test
    public void testServcie(){
        User user = userService.getById(1);
        System.out.println(user);
    }
    

    image-20230306124359229

2、多行查询

image-20230306125349084

  1. 根据ID批量查询

    @Test
    public void testServcie(){
        List<Integer> list = Arrays.asList(1, 2, 3);
        List<User> users = userService.listByIds(list);
        users.forEach(System.out::println);
    }
    

    image-20230306124647126

  2. 查询所有

    @Test
    public void testServcie(){
        //返回list
     	List<User> list = userService.list();
        System.out.println(list);
        //返回map
        List<Map<String, Object>> maps = userService.listMaps();
        System.out.println(maps);
    
        List<Object> objects = userService.listObjs();
        System.out.println(objects);
    }
    

    image-20230306125554522

3.2.3、删除

image-20230306115936178

  1. 根据id删除

    @Test
    public void testServcie(){
        boolean b = userService.removeById(21);
    }
    
    image-20230306120252382
  2. 根据实体的id删除

    @Test
    public void testServcie(){
        User user = userService.getById(22);
        boolean b = userService.removeById(user);
    }
    
    image-20230306120455791
  3. 批量删除

    @Test
    public void testServcie(){
        List<Integer> list = Arrays.asList(23, 24, 25);
        boolean b = userService.removeByIds(list);
    }
    
    image-20230306120634151
  4. 根据Map条件删除

    @Test
    public void testServcie(){
        Map<String ,Object> map = new HashMap<>();
        map.put("username","批量增加5");
        map.put("password","123");
        boolean b = userService.removeByMap(map);
    }
    
    image-20230306120900709
3.2.4、修改

image-20230306121504141

  1. 根据ID修改

    @Test
    public void testServcie(){
        User user = userService.getById(27);
        user.setUsername("修改1");
        user.setPassword("213123");
        boolean b = userService.updateById(user);
    }
    
    image-20230306121740680
  2. 批量修改

    @Test
    public void testServcie(){
        List<Integer> list = Arrays.asList(28, 29, 30);
        List<User> users = userService.listByIds(list);
        users.forEach(user -> {
            user.setUsername("批量修改");
        });
        boolean b = userService.updateBatchById(users);
    }
    
    image-20230306122251212
3.2.5、修改或更新

image-20230306115225586

3.2.6、分页
image-20230306125813443

在Mybatis-plus中提供了有关分页的接口和实现类 IPage 和 Page

public class Page<T> implements IPage<T> {
    private static final long serialVersionUID = 8545996863226528798L;
    //用来存放查询出来的数据
    protected List<T> records = Collections.emptyList();
    //返回的数据总数
    protected long total = 0;
    // 每页显示条数,默认 10
    protected long size = 10;
    //当前页,默认1
    protected long current = 1;
    // 排序字段信息
    @Setter
    protected List<OrderItem> orders = new ArrayList<>();
    //自动优化 COUNT SQL
    protected boolean optimizeCountSql = true;
    // 是否进行 count 查询
    protected boolean searchCount = true;
  
    public Page() {
    }

    /**
     * 有参构造函数
     * @param current 当前页
     * @param size    每页显示条数
     */
    public Page(long current, long size) {
        this(current, size, 0);
    }

    public Page(long current, long size, long total) {
        this(current, size, total, true);
    }

    public Page(long current, long size, boolean searchCount) {
        this(current, size, 0, searchCount);
    }

    public Page(long current, long size, long total, boolean searchCount) {
        if (current > 1) {
            this.current = current;
        }
        this.size = size;
        this.total = total;
        this.searchCount = searchCount;
    }

    //是否存在上一页
    public boolean hasPrevious() {
        return this.current > 1;
    }

    //是否存在下一页
    public boolean hasNext() {
        return this.current < this.getPages();
    }
    ..........
}
  • 配置

    • 使用Spring时,在Spring的配置文件中先配置mybatis-plus内置的分页插件

      <!-- 配置mybatis-plus的分页拦截器-->
      <bean id="paginationInnerInterceptor" class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor"/>
          
      <!-- 配置mybatis-plus的分页拦截器插件 -->
      <bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
          <property name="interceptors" >
              <list>
                  <ref bean="paginationInnerInterceptor"/>
              </list>
          </property>
      </bean>
      <!-- 将插件加入到MybatisSqlSessionFactoryBean 中-->
      <bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
          <!--加载连接池-->
          <property name="dataSource" ref="dataSource"/>
          <!-- 设置MyBatis配置文件的路径(可以不设置) -->
          <property name="configLocation" value="classpath:mybatis-config.xml"/>
          <!--加载映射文件路径-->
          <property name="mapperLocations" value="classpath:mapping/*.xml"/>
          <!--分页插件生效 -->
          <property name="plugins">
              <array>
                  <ref bean="mybatisPlusInterceptor"/>
              </array>
          </property>
      </bean>
      
    • 使用SpringBoot时配置时,在配置类中配置

      @Bean
      public MybatisPlusInterceptor mybatisPlusInterceptor() {
          MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
          interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
          return interceptor;
      }
      
  • 分页查询数据

    @Test
    public void testServcie(){
        Page<User> page = userService.page(new Page<>(1,5));
        System.out.println("总数据:"+page.getTotal());
        List<User> users = page.getRecords();
        users.forEach(System.out::println);
    }
    

    image-20230306133721050

3.2.7、查询记录数
image-20230306133903188
@Test
public void testServcie(){
    long count = userService.count();
    System.out.println(count);
}

image-20230306134002194

### 使用 MyBatis-Plus 实现服务 MyBatis-Plus 是一个增强版的 MyBatis 框架,简化了数据库操作并提供了丰富的特性来加速开发过程。对于服务实现而言,通常会遵循分架构模式,在此模式下,业务逻辑被封装在独立的服务类中。 #### 创建实体类服务接口 首先定义与数据库表对应的实体类,并创建相应的 Mapper 接口继承 `BaseMapper`: ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public class User { private Long id; private String name; } interface UserMapper extends BaseMapper<User> {} ``` 接着编写服务接口及其默认方法声明[^2]: ```java import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.IService; @Service public interface IUserService extends IService<User> { } ``` #### 编写具体的服务实现类 为了提供具体的业务处理能力,需构建服务实现类,该类负责调用数据访问对象(DAO),即上述提到的 Mapper 来完成 CRUD 操作以及其他复杂查询需求: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @Autowired private UserMapper userMapper; public List<User> getUsersByName(String name){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", name); return this.list(queryWrapper); } } ``` 通过这种方式可以快速搭建起基于 MyBatis-Plus 的服务结构,利用框架自带的功能减少重复编码工作量的同时也提高了代码可读性维护性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰 羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值