SSMP小案例Service层

编写Service接口
```
public interface BookService {
Boolean save(Book book);
Boolean delete(Integer id);
Boolean update(Book book);
Book getById(Integer id);
List<Book> getAll();
IPage<Book> getByPage(int currentPage, int pageSize);
}
```
实现service接口
```
@Service
public class BookServiceImpl2 implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public Boolean save(Book book) {
return bookMapper.insert(book)>0;
}
@Override
public Boolean delete(Integer id) {
return bookMapper.deleteById(id)>0;
}
@Override
public Boolean update(Book book) {
return bookMapper.updateById(book)>0;
}
@Override
public Book getById(Integer id) {
return bookMapper.selectById(id);
}
@Override
public List<Book> getAll() {
return bookMapper.selectList(null);
}
@Override
public IPage<Book> getByPage(int currentPage, int pageSize) {
IPage page = new Page(currentPage,pageSize);
return bookMapper.selectPage(page,null);
}
}
```
这里需要注意一下,因为返回的是Boolean类型,所以要写>0进行逻辑判断。

然后就是编写service的测试用例
```
@SpringBootTest
public class BookServiceTestCase {
@Autowired
private Book book;
@Autowired
private BookService bookService;
@Test
void testGetById(){
System.out.println(bookService.getById(4));
}
/**
* 测试增加
*/
@Test
void testSave(){
book.setType("测试数据123");
book.setName("测试数据123");
book.setDescription("测试数据123");
bookService.save(book);
}
/**
* 测试更新
*/
@Test
void testUpdate(){
book.setId(5);
book.setType("测试数据123aaa");
book.setName("测试数据123sds");
book.setDescription("测试数据123aaa");
bookService.update(book);
}
/**
* 测试删除
*/
@Test
void testDelete(){
System.out.println(bookService.delete(19));
}
/**
* 测试查询全部
*/
@Test
void testGetAll(){
System.out.println(bookService.getAll());
}
/**
* 测试分页
*/
@Test
void testGetPage(){
IPage<Book> page = bookService.getByPage(2, 5);
System.out.println(page.getCurrent());//当前的页码
System.out.println(page.getSize());//每页多少数据
System.out.println(page.getTotal());//总记录条数
System.out.println(page.getRecords());//数据
}
}
```

浙公网安备 33010602011771号