自定义接口
/**
* 自定义接口,统一管理所有方法
*
*/
public interface BrandService {
List<Brand> selectAll();
void addBrand(Brand brand);
void deleteById(Integer id);
void deleteByIds(int[] ids);
void updateBrand(Brand brand);
PageBean<Brand> selectByPage(int currentPage, int pageSize);
PageBean<Brand> selectBrand(int currentPage, int pageSize,Brand brand);
}
定义类实现接口并且重写接口中的方法
/**
* 实现类实现自定义接口
* 并且重写接口中的方法
*/
public class BrandServiceImpl implements BrandService {
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
@Override
public List<Brand> selectAll() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectAll();
sqlSession.close();
return brands;
}
@Override
public void addBrand(Brand brand) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.addBrand(brand);
sqlSession.close();
}
@Override
public void deleteById(Integer id) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteById(id);
sqlSession.close();
}
@Override
public void deleteByIds(int[] ids) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteByIds(ids);
sqlSession.close();
}
@Override
public void updateBrand(Brand brand) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.updateBrand(brand);
sqlSession.close();
}
/**
* 方法主要进行分页查询
* @param currentPage
* @param pageSize
* @return
*/
@Override
public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//需要计算出开始的查询的索引
//使用当前页面减1乘上每页条数
int begin = (currentPage - 1) * pageSize;
List<Brand> brands = mapper.selectByPage(begin, pageSize);
//查询一共有多少条数据
int TotalCount = mapper.selectTotalCount();
//将数据封装进自定义的实体类对象中
PageBean pageBean = new PageBean();
pageBean.setRows(brands);
pageBean.setTotalCount(TotalCount);
sqlSession.close();
return pageBean;
}
/**
* 和分页查询类似,只是附带上条件查询
* @param currentPage
* @param pageSize
* @param brand
* @return
*/
@Override
public PageBean<Brand> selectBrand(int currentPage, int pageSize,Brand brand) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
int begin = (currentPage - 1) * pageSize;
//这次调用的方法要带上查询条件
List<Brand> brands = mapper.selectBrand(begin,pageSize,brand);
int TotalCount = mapper.selectBrandTotalCount(brand);
PageBean pageBean = new PageBean();
pageBean.setRows(brands);
pageBean.setTotalCount(TotalCount);
sqlSession.close();
return pageBean;
}
}