web项目的结构分为三层:DAO层,Service层、Web层
MybatisPlus入门demo(上一篇)使用mybatis封装Dao层,本篇文章使用MybatisPlus封装service
基础理论
MP封装services层:
1、添加Service接口**继承 IService<实体类>
2、添加Service实现类实现接口、继承Servicelmpl<mapper、实体类>
1、创建Service接口
IService 是由MP封装的。
package com.atguigu.auth.service;
import com.atguigu.model.system.SysRole;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface sysRoleService extends IService<SysRole> {
}
2、创建Service实现类
ServiceImpl是由MP封装的
ServiceImpl<SysRoleMapper, SysRole> 是将SysRoleMapper进行自动注入并且设置为baseMapper,baseMapper里面有封装好的CRUD操作
package com.atguigu.auth.service.impl;
import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.model.system.SysRole;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.auth.service.sysRoleService;
@Service
public class sysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements sysRoleService {
//ServiceImpl 源码里实现了自动注入,可是要是不写下面两行手动注入会找不到唯一的bean不知道为什么
@Autowired
private SysRoleMapper sysRoleMapper;
}
3、测试
注入service进行测试
package com.atguigu.auth;
import com.atguigu.model.system.SysRole;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.atguigu.auth.service.sysRoleService;
import org.springframework.boot.test.context.TestComponent;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemo2 {
@Autowired
private sysRoleService service;
@Test
public void getAll() {
List<SysRole> list = service.list();
System.out.println(list);
}
}