接着上一篇mybatis代码生成插件,这里所需的依赖都在上一篇中 这里介绍的是项目中用的mybatis查询和分页封装
AbstractService.java
public abstract class AbstractService<T> implements Service<T> {
@Autowired
protected MyMapper<T> mapper;
private Class<T> modelClass; // 当前泛型真实类型的Class
public AbstractService() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
}
@Override
public boolean save(T model) {
return mapper.insertSelective(model) > 0;
}
@Override
public void save(List<T> models) {
mapper.insertList(models);
}
@Override
public boolean deleteById(Long id) {
return mapper.deleteByPrimaryKey(id) > 0;
}
@Override
public void deleteByIds(String ids) {
mapper.deleteByIds(ids);
}
@Override
public boolean update(T model) {
return mapper.updateByPrimaryKeySelective(model) > 0;
}
@Override
public boolean updateByConditionSelective(T model, Condition condition) {
return mapper.updateByConditionSelective(model, condition) > 0;
}
@Override
public T findById(Integer id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public T findBy(String fieldName, Object value) {
try {
T model = modelClass.newInstance();
Field field = modelClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(model, value);
return mapper.selectOne(model);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public List<T> findByIds(String ids) {
return mapper.selectByIds(ids);
}
@Override
public List<T> findByCondition(Condition condition) {
return mapper.selectByCondition(condition);
}
@Override
public List<T> findAll() {
return mapper.selectAll();
}
@Override
public T findById(Long id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public int selectCountByCondition(Condition condition) {
return mapper.selectCountByCondition(condition);
}
@Override
public MyPageInfo<T> pageList(Condition condition, PageParam pageParam) {
PageHelper.startPage(pageParam.getCurrentPage(), pageParam.getPageSize());
if (!StringUtils.isEmpty(pageParam.getSort()) && !StringUtils.isEmpty(pageParam.getOrder())) {
PageHelper.orderBy(new StringBuffer().append(pageParam.getSort()).append(" ").append(pageParam.getOrder()).toString());
}
List<T> list = this.findByCondition(condition);
if (CollectionUtils.isEmpty(list)) {
return null;
}
MyPageInfo<T> myPageInfo = new MyPageInfo<>(list);
return myPageInfo;
}
}
复制代码
MyMapper.java(接口)
public interface MyMapper<T>
extends
BaseMapper<T>,
ConditionMapper<T>,
IdsMapper<T>,
InsertListMapper<T> {
}
复制代码
Service.java
public interface Service<T> {
boolean save(T model);//持久化
void save(List<T> models);//批量持久化
boolean deleteById(Long id);//通过主鍵刪除
void deleteByIds(String ids);//批量刪除 eg:ids -> “1,2,3,4”
boolean update(T model);//更新
boolean updateByConditionSelective(T model, Condition condition);//根据条件更新
T findById(Integer id);//通过ID查找
T findById(Long id);//通过ID查找
T findBy(String fieldName, Object value); //通过Model中某个成员变量名称(非数据表中column的名称)查找,value需符合unique约束
List<T> findByIds(String ids);//通过多个ID查找//eg:ids -> “1,2,3,4”
List<T> findByCondition(Condition condition);//根据条件查找
List<T> findAll();//获取所有
int selectCountByCondition(Condition condition); //count
MyPageInfo<T> pageList(Condition condition, PageParam pageParam); //分页
}
复制代码
MyPageInfo.java
@Data
public class MyPageInfo<T> implements Serializable {
private static final long serialVersionUID = 1L;
//当前页
private int currentPage;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//排序
private String orderBy;
// 排序字段
private String sort;
// 排序规则,asc/desc
private String order;
//当前页面第一个元素在数据库中的行号
private int startRow;
//当前页面最后一个元素在数据库中的行号
private int endRow;
//总记录数
private long total;
//总页数
private int pages;
//结果集
private List<T> list;
public MyPageInfo() {
}
/**
* 包装Page对象
*
* @param list
*/
public MyPageInfo(List<T> list) {
this(list, 8);
}
/**
* 包装Page对象
*
* @param list page结果
* @param navigatePages 页码数量
*/
public MyPageInfo(List<T> list, int navigatePages) {
if (list instanceof Page) {
Page page = (Page) list;
this.currentPage = page.getPageNum();
this.pageSize = page.getPageSize();
this.orderBy = page.getOrderBy();
// 设置排序字段和排序规则
if (!StringUtils.isEmpty(page.getOrderBy())) {
String[] array = page.getOrderBy().split(" ");
this.sort = array[0];
this.order = array[1];
}
this.pages = page.getPages();
this.list = page;
this.size = page.size();
this.total = page.getTotal();
//由于结果是>startRow的,所以实际的需要+1
if (this.size == 0) {
this.startRow = 0;
this.endRow = 0;
} else {
this.startRow = page.getStartRow() + 1;
//计算实际的endRow(最后一页的时候特殊)
this.endRow = this.startRow - 1 + this.size;
}
} else if (list instanceof Collection) {
this.currentPage = 1;
this.pageSize = list.size();
this.pages = 1;
this.list = list;
this.size = list.size();
this.total = list.size();
this.startRow = 0;
this.endRow = list.size() > 0 ? list.size() - 1 : 0;
}
}
@Override
public String toString() {
return "MyPageInfo{" +
"currentPage=" + currentPage +
", pageSize=" + pageSize +
", size=" + size +
", orderBy='" + orderBy + '\'' +
", startRow=" + startRow +
", endRow=" + endRow +
", total=" + total +
", pages=" + pages +
", list=" + list +
'}';
}
}
复制代码
PageParam.java
@Data
public class PageParam implements Serializable {
/**
* 分页排序常用数据库字段定义
*/
public static final String CREATE_TIME = "create_time";
public static final String MODIFY_TIME = "modify_time";
public static final String DESC = "desc";
public static final String ASC = "asc";
// 当前页
@NotNull(message = "当前页不能为空")
@Min(value = 1, message = "当前页不能小于1")
private Integer currentPage;
// 每页记录数
@NotNull(message = "每页记录数不能为空")
@Max(value = 20, message = "每页记录数不能超过20")
private Integer pageSize;
// 排序字段
private String sort;
// 排序规则,asc/desc
private String order;
public PageParam() {
}
/**
* 构建不带排序规则的分页参数
*
* @param currentPage
* @param pageSize
*/
public static PageParam build(Integer currentPage, Integer pageSize) {
PageParam pageParam = new PageParam();
pageParam.setCurrentPage(currentPage);
pageParam.setPageSize(pageSize);
return pageParam;
}
/**
* 构建带排序规则的分页参数
*
* @param currentPage
* @param pageSize
* @param sort
* @param order
*/
public static PageParam build(Integer currentPage, Integer pageSize, String sort, String order) {
PageParam pageParam = new PageParam();
pageParam.setCurrentPage(currentPage);
pageParam.setPageSize(pageSize);
pageParam.setSort(sort);
pageParam.setOrder(order);
return pageParam;
}
/**
* 构建默认按照创建时间倒序排序的分页参数(前提:数据库表必须有create_time字段)
*
* @return
*/
public static PageParam buildWithDefaultSort(Integer currentPage, Integer pageSize) {
PageParam pageParam = new PageParam();
pageParam.setCurrentPage(currentPage);
pageParam.setPageSize(pageSize);
pageParam.setSort(CREATE_TIME);
pageParam.setOrder(DESC);
return pageParam;
}
}
复制代码
PageUtil.java
@Slf4j
public class PageUtil {
/**
* 分页对象转换
*
* @param myPageInfo
* @param classType
* @param <T>
* @return
*/
public static <T> MyPageInfo<T> transform(MyPageInfo<?> myPageInfo, Class<T> classType) {
if (myPageInfo == null) {
return new MyPageInfo<>();
}
MyPageInfo<T> pageInfoResult = new MyPageInfo<>();
try {
pageInfoResult.setList(copyList(myPageInfo.getList(), classType));
} catch (Exception e) {
log.error("transform error", e);
}
pageInfoResult.setCurrentPage(myPageInfo.getCurrentPage());
pageInfoResult.setPageSize(myPageInfo.getPageSize());
pageInfoResult.setSize(myPageInfo.getSize());
pageInfoResult.setOrderBy(myPageInfo.getOrderBy());
pageInfoResult.setStartRow(myPageInfo.getStartRow());
pageInfoResult.setEndRow(myPageInfo.getEndRow());
pageInfoResult.setTotal(myPageInfo.getTotal());
pageInfoResult.setPages(myPageInfo.getPages());
pageInfoResult.setSort(myPageInfo.getSort());
pageInfoResult.setOrder(myPageInfo.getOrder());
return pageInfoResult;
}
/**
* 转换对象并复制至list
*
* @param source
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> copyList(List<?> source, Class<T> clazz) {
if (source == null || source.size() == 0) {
return Collections.emptyList();
}
List<T> res = new ArrayList<>(source.size());
for (Object o : source) {
try {
T t = clazz.newInstance();
res.add(t);
BeanUtils.copyProperties(o, t);
} catch (Exception e) {
log.error("copyList error", e);
}
}
return res;
}
}
复制代码