MyBatis-Plus streamliens service creation by extending the IService interface. Begin by declaring a role service contract:
public interface ISysRoleService extends IService<SysRole> {
}
The default implemantation uses ServiceImpl, which handles dependency injection of the maper:
@Service
public class SysRoleService extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
// The baseMapper field is auto-wired from the Mapper interface provided in the type parameters.
}
With the service in place, create a test class to verify operations:
@SpringBootTest
public class RoleServiceTest {
@Autowired
private ISysRoleService roleService;
}
Fetching all roles
@Test
void testRetrieveAll() {
List<SysRole> roles = roleService.list();
roles.forEach(System.out::println);
}
Adding a new role
@Test
void testAddRole() {
SysRole role = new SysRole();
role.setRoleName("Administrator");
role.setRoleCode("admin");
role.setDescription("Full system access role");
boolean saved = roleService.save(role);
System.out.println(saved);
System.out.println(role);
}
Modifying a role's code
@Test
void testModifyRoleCode() {
SysRole role = new SysRole();
role.setId(20L);
role.setRoleCode("supervisor");
boolean updated = roleService.updateById(role);
System.out.println(updated);
}
Deleting a role by ID
@Test
void testRemoveRole() {
boolean removed = roleService.removeById(25);
System.out.println(removed);
}
Batch deletion
@Test
void testBatchRemove() {
boolean result = roleService.removeByIds(Arrays.asList(3, 8));
System.out.println(result);
}
Conditional querying with LambdaQueryWrapper
@Test
void testQueryByCondition() {
LambdaQueryWrapper<SysRole> lambdaQuery = new LambdaQueryWrapper<>();
lambdaQuery.eq(SysRole::getRoleCode, "supervisor");
List<SysRole> roles = roleService.list(lambdaQuery);
roles.forEach(System.out::println);
}
Note: When using
@MapperScan, ensure the base package points exactly to the mapper package (not a parent package) to prevent scanning conflicts and startup errors.