项目GitHub地址 :
https://github.com/FrameReserve/TrainingBoot
Spring Boot (三)集成spring security,标记地址:
https://github.com/FrameReserve/TrainingBoot/releases/tag/0.0.4
思路为:
BaseEntity
BaseDao,实现类分支:MyBatis、Redis
BaseService,实现类分支:MyBatis、Redis
BaseController,实现类分支:统一异常处理、MyBatis(增删改查,模糊分页)、MyBatis(读)、Redis(增删改查)
ResultDataDto,统一Json数据交互格式。
自定义异常类:业务逻辑异常;功能不完善;网络异常;其它异常。(权限异常由Spring Security处理,本章略)
------------------------------------------------------------------------------------------
BaseEntity,统一父类,实现反射,泛型动态实现统一增删改查。
src/main/java/com/training/core/entity/BaseEntity.java
package com.training.core.entity; import java.io.Serializable; import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; import tk.mybatis.mapper.annotation.NameStyle; import tk.mybatis.mapper.code.Style; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @NameStyle(value = Style.camelhumpAndLowercase) public class BaseEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonProperty("id") private Integer id; /** * 创建时间 */ @Column private Date createTime; /** * 最后修改时间 */ @Column private Date lastModifyTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastModifyTime() { return lastModifyTime; } public void setLastModifyTime(Date lastModifyTime) { this.lastModifyTime = lastModifyTime; } }
定义BaseDao接口,统一增删改查规范:
src/main/java/com/training/core/dao/BaseDao.java
package com.training.core.dao; import java.util.List; import tk.mybatis.mapper.entity.Example; import com.training.core.dto.FlexiPageDto; import com.training.core.entity.BaseEntity; public interface BaseDao<T extends BaseEntity> { /** * 根据Id查询实体 */ public T getEntityById(final Class<T> cls, final Integer id); /** * 新增实体 */ public void addEntity(final T entity); /** * 更新实体 */ public void updateEntity(final T entity); /** * 根据Id删除实体 */ public void deleteEntityById(final Class<T> cls, final Integer id); /** * 查询全部 */ public List<T> selectAll(Class<T> cls); /** * 单表模糊查询 */ public List<T> findByLike(Example example); /** * 根据模糊分页查询 */ public List<T> findByPage(Example example, FlexiPageDto flexiPageDto); /** * 单表模糊查询总记录数 */ public int findRowCount(Example example); }
MyBatis BaseDao实现:
src/main/java/com/training/core/dao/impl/MyBatisBaseDaoImpl.java
package com.training.core.dao.impl; import java.util.List; import javax.annotation.Resource; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.entity.Example; import com.training.core.annotation.MapperClass; import com.training.core.dao.BaseDao; import com.training.core.dto.FlexiPageDto; import com.training.core.entity.BaseEntity; @Repository("myBatisBaseDao") @SuppressWarnings("unchecked") public class MyBatisBaseDaoImpl<T extends BaseEntity> implements BaseDao<T> { @Resource @Qualifier("sessionFactory") private SqlSessionFactory sqlSessionFactory; private SqlSession sqlSession; @SuppressWarnings("rawtypes") public <M extends Mapper<T>> M getMapper(Class cls){ MapperClass mapperClass = (MapperClass) cls.getAnnotation(MapperClass.class); if(null == mapperClass){ throw new RuntimeException("没有注解MapperClass"); } return (M) getSqlSession().getMapper(mapperClass.value()); } @Override public T getEntityById(Class<T> cls, Integer id) { return this.getMapper(cls).selectByPrimaryKey(id); } @Override public void addEntity(T entity) { this.getMapper(entity.getClass()).insert(entity); } @Override public void updateEntity(T entity) { this.getMapper(entity.getClass()).updateByPrimaryKey(entity); } @Override public void deleteEntityById(Class<T> cls, Integer id) { this.getMapper(cls).deleteByPrimaryKey(id); } @Override public List<T> selectAll(Class<T> cls) { return this.getMapper(cls).selectAll(); } @Override public List<T> findByLike(Example example) { return this.getMapper(example.getEntityClass()).selectByExample(example); } @Override public List<T> findByPage(Example example, FlexiPageDto flexiPageDto) { RowBounds rowBounds = new RowBounds(flexiPageDto.getOffset(), flexiPageDto.getRp()); return this.getMapper(example.getEntityClass()).selectByExampleAndRowBounds(example, rowBounds); } @Override public int findRowCount(Example example) { return this.getMapper(example.getEntityClass()).selectCountByExample(example); } public SqlSession getSqlSession(){ if (null == sqlSession){ synchronized (MyBatisBaseDaoImpl.class) { this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); } } return this.sqlSession; } }
Redis统一增删改查,再下一章讲解,本章略。
定义BaseService接口,统一增删改查规范:
src/main/java/com/training/core/service/BaseService.java
package com.training.core.service; import com.training.core.entity.BaseEntity; import java.util.List; public interface BaseService<T extends BaseEntity> { /** * 根据Id查询实体 */ T getEntityById(final Integer id); /** * 新增实体 */ void addEntity(final T entity); /** * 更新实体 */ void updateEntity(final T entity); /** * 根据Id删除实体 */ void deleteEntityById(final Integer id); /** * 查询所有 */ List<T> selectAll(); }
MyBatis BaseService实现:
src/main/java/com/training/core/dao/impl/MyBatisBaseDaoImpl.java
package com.training.core.service.impl; import javax.annotation.Resource; import com.training.core.dao.BaseDao; import com.training.core.dao.impl.MyBatisBaseDaoImpl; import com.training.core.entity.BaseEntity; import com.training.core.service.BaseService; import com.training.core.util.GenericeClassUtils; import tk.mybatis.mapper.common.Mapper; import java.util.List; public class MyBatisBaseServiceImpl<T extends BaseEntity> implements BaseService<T> { @SuppressWarnings("unchecked") protected Class<T> entityClass = (Class<T>) GenericeClassUtils.getSuperClassGenricType(this.getClass(), 0); protected <M extends Mapper<T>> M getMapper(Class cls){ return ((MyBatisBaseDaoImpl<T>) baseDao).getMapper(cls); } @Resource(name = "myBatisBaseDao") private BaseDao<T> baseDao; @Override public T getEntityById(Integer id) { return baseDao.getEntityById(entityClass, id); } @Override public void addEntity(T entity) { baseDao.addEntity(entity); } @Override public void updateEntity(T entity) { baseDao.updateEntity(entity); } @Override public void deleteEntityById(Integer id) { baseDao.deleteEntityById(entityClass, id); } @Override public List<T> selectAll() { return baseDao.selectAll(entityClass); } }
定义Base Controller,统一异常处理:
为了兼容IE8,解决弹出下载文件框,使用传统流输出模式。
src/main/java/com/training/core/controller/BaseController.java
package com.training.core.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.ExceptionHandler; import com.google.gson.Gson; import com.training.core.dto.ResultDataDto; import com.training.core.entity.BaseEntity; public class BaseController<T extends BaseEntity> { // 异常信息拦截,统一处理返回,为了兼容IE8,用流方式输出 @ExceptionHandler(Exception.class) //在Controller类中添加该注解方法即可(注意:添加到某个controller,只针对该controller起作用) public void exceptionHandler(Exception ex, HttpServletResponse response, HttpServletRequest request) throws IOException { ResultDataDto resultDataDto = new ResultDataDto(ex); response.setContentType("text/html;charset=utf-8"); response.getWriter().write(new Gson().toJson(resultDataDto)); } }
Base Crud Controller,增删改查Controller,根据URL参数实现统一模糊、分页动态查询
src/main/java/com/training/core/controller/BaseCrudController.java
package com.training.core.controller; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import java.util.List; import javax.annotation.Resource; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import tk.mybatis.mapper.entity.Example; import com.training.core.dao.BaseDao; import com.training.core.dto.FlexiPageDto; import com.training.core.dto.ResultDataDto; import com.training.core.entity.BaseEntity; import com.training.core.util.FilterUtil; import com.training.core.util.GenericeClassUtils; public class BaseCrudController<T extends BaseEntity> extends BaseController<T> { @SuppressWarnings("unchecked") protected Class<T> entityClass = (Class<T>) GenericeClassUtils.getSuperClassGenricType(this.getClass(), 0); @Resource(name = "myBatisBaseDao") protected BaseDao<T> baseDao; /** * 根据Id查询实体 */ @ApiOperation(value="根据Id查询实体", notes="getEntityById") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer") @RequestMapping(value = "/getEntityById/{id}", method = RequestMethod.GET) public @ResponseBody ResultDataDto getEntityById(@PathVariable(value = "id") final Integer id) { T entity = baseDao.getEntityById(entityClass, id); return new ResultDataDto(entity); } /** * 新增实体 */ @ApiOperation(value="新增实体", notes="addEntity") @ApiImplicitParam(name = "entity", value = "实体Json", required = true, dataType = "application/json") @RequestMapping(value = "/addEntity", method = RequestMethod.POST, consumes = "application/json") @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED) public @ResponseBody ResultDataDto addEntity(@RequestBody final T entity) { baseDao.addEntity(entity); return ResultDataDto.addAddSuccess(); } /** * 更新实体 */ @ApiOperation(value="更新实体", notes="updateEntity") @ApiImplicitParam(name = "entity", value = "实体Json", required = true, dataType = "application/json") @RequestMapping(value = "/updateEntity", method = RequestMethod.PUT, consumes = "application/json") @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED) public @ResponseBody ResultDataDto updateEntity(@RequestBody final T entity) { baseDao.updateEntity(entity); return ResultDataDto.addUpdateSuccess(); } /** * 根据Id删除实体 */ @ApiOperation(value="根据Id删除实体", notes="deleteEntityById") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer") @RequestMapping(value = "/deleteEntityById/{id}", method = RequestMethod.DELETE) @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED) public @ResponseBody ResultDataDto deleteEntityById(@PathVariable(value = "id") final Integer id) { baseDao.deleteEntityById(entityClass, id); return ResultDataDto.addDeleteSuccess(); } /** * 查询所有实体 */ @ApiOperation(value="查询所有实体", notes="findAllEntitys") @SuppressWarnings({ "rawtypes", "unchecked" }) @RequestMapping(value = "/findAllEntitys", method = RequestMethod.GET) public @ResponseBody ResultDataDto findAllEntitys() { List list = baseDao.selectAll(entityClass); return new ResultDataDto(list); } /** * 分页模糊查询 * * @param pageNumber 当前页 * @param pageSize 每页显示数 * @param orderBy 排序条件 * &orderBy=name_desc,id_asc * * @param filter 模糊查询条件 * * 查询条件说明:&filter= * id_L_3_EQ__, * * 属性(id) _ 类型(Long) _ 值(3) _ EQ(精确查询) _ AND(默认And查询) _ , * * 类型: * S(String.class), I(Integer.class), L(Long.class), B(Boolean.class), * C(Collection.class) 例:1,2,3,4,5。使用,间隔。 * * 匹配模式: * IN 例: select * from tableName where id in (1,2,3,4,5); * EQ, 例: select * from tableName where id = 1; * LIKE, 例: select * from tableName where name like '%张三%'; * LT, 例: select * from tableName where id < 100; * GT, 例: select * from tableName where id > 100; * LE, 例: select * from tableName where id <= 100; * GE 例: select * from tableName where id >= 100; * * * 完整案例: * select * from tableName where id = 3 and name = '张三' limit 0, 10 * http://localhost:8080/syssetting/findLikePage?pageNumber=1&pageSize=10&orderBy=&filter=id_L_2_EQ__,name_S_资源_LIKE__& * * OR案例: * select * from tableName where (id = 3 or name = '张三') or name = '李四' limit 0, 10 * &filter=id_L_3_EQ_OR_,name_S_张三_EQ_OR_,name_S_李四_EQ_OR_ * * * */ @ApiOperation(value="分页模糊查询", notes="findLikePage") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNumber", value = "当前页", required = true, dataType = "Integer"), @ApiImplicitParam(name = "pageSize", value = "每页显示数", required = true, dataType = "Integer"), @ApiImplicitParam(name = "orderBy", value = "排序:name_desc,id_asc", required = true, dataType = "String"), @ApiImplicitParam(name = "filter", value = "过滤规则:&filter=id_L_3_EQ_OR_,name_S_张三_EQ_OR_,name_S_李四_EQ_OR_", required = true, dataType = "String") }) @RequestMapping(value = "/findLikePage", method = RequestMethod.GET) public @ResponseBody ResultDataDto findLikePage(@RequestParam("pageNumber") Integer pageNumber, @RequestParam("pageSize") Integer pageSize, @RequestParam("orderBy") String orderBy, @RequestParam("filter") String filterStr) { Example example = FilterUtil.parsePropertyFilterExp(entityClass, filterStr, orderBy); FlexiPageDto flexiPageDto = new FlexiPageDto(pageNumber, pageSize); List<T> list = this.baseDao.findByPage(example, flexiPageDto); return new ResultDataDto(list); } @ApiOperation(value="分页模糊查询总记录数", notes="findLikePageRowCount") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNumber", value = "当前页", required = true, dataType = "Integer"), @ApiImplicitParam(name = "pageSize", value = "每页显示数", required = true, dataType = "Integer"), @ApiImplicitParam(name = "orderBy", value = "排序:name_desc,id_asc", required = true, dataType = "String"), @ApiImplicitParam(name = "filter", value = "过滤规则:&filter=id_L_3_EQ_OR_,name_S_张三_EQ_OR_,name_S_李四_EQ_OR_", required = true, dataType = "String") }) @RequestMapping(value = "/findLikePageRowCount", method = RequestMethod.GET) public @ResponseBody ResultDataDto findLikePageRowCount(@RequestParam("pageNumber") Integer pageNumber, @RequestParam("pageSize") Integer pageSize, @RequestParam("orderBy") String orderBy, @RequestParam("filter") String filterStr) { Example example = FilterUtil.parsePropertyFilterExp(entityClass, filterStr, orderBy); Integer count = this.baseDao.findRowCount(example); return new ResultDataDto().setCode(ResultDataDto.CODE_SUCCESS).setDatas(count); } }
------------------------------------------------------------------------------------------
辅助类、自定义异常
统一Json传输对象ResultDataDto:
src/main/java/com/training/core/dto/ResultDataDto.java
package com.training.core.dto; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.google.gson.Gson; import com.training.core.entity.BaseEntity; import com.training.core.exception.RuntimeFunctionException; import com.training.core.exception.RuntimeOtherException; import com.training.core.exception.RuntimeServiceException; import com.training.core.exception.RuntimeWebException; @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class ResultDataDto { /** * 200-成功 */ public final static String CODE_SUCCESS = "200"; /** * 301-代表永久性转移 */ public final static String CODE_PERMANENTLY_MOVED = "301"; /** * 500-业务逻辑错误 */ public final static String CODE_ERROR_SERVICE = "500"; /** * 501-功能不完善,无对应方法 */ public final static String CODE_ERROR_FUNCTION = "501"; /** * 502-网络异常 */ public final static String CODE_ERROR_WEB = "502"; /** * 503-未知其它 */ public final static String CODE_ERROR_OTHER = "503"; /** * 文件流导入返回值,因IE不支持json返回 * @return */ public static void addImportSuccess(HttpServletResponse response, String message) { try { response.setContentType("text/html"); response.getWriter().write(new Gson().toJson(ResultDataDto.addSuccess(message))); } catch (IOException e) { throw new RuntimeServiceException(e); } } /** * 文件流导入返回值,因IE不支持json返回 * @return */ public static void addImportSuccess(HttpServletResponse response) { try { response.setContentType("text/html"); response.getWriter().write(new Gson().toJson(ResultDataDto.addSuccess("上传成功"))); } catch (IOException e) { throw new RuntimeServiceException(e); } } public static void addImportError(HttpServletResponse response, String message) { try { response.setContentType("text/html"); response.getWriter().write(new Gson().toJson(new ResultDataDto(CODE_ERROR_SERVICE, message))); } catch (IOException e) { throw new RuntimeServiceException(e); } } public static ResultDataDto addSuccess() { return new ResultDataDto(CODE_SUCCESS, null); } public static ResultDataDto addSuccess(String message) { return new ResultDataDto(CODE_SUCCESS, message); } public static ResultDataDto addAddSuccess() { return new ResultDataDto(CODE_SUCCESS, "新增成功"); } public static ResultDataDto addUpdateSuccess() { return new ResultDataDto(CODE_SUCCESS, "更新成功"); } public static ResultDataDto addUpdateCheckSuccess() { return new ResultDataDto(CODE_SUCCESS, "确定成功"); } public static ResultDataDto addDeleteSuccess() { return new ResultDataDto(CODE_SUCCESS, "删除成功"); } public static ResultDataDto addOperationSuccess() { return new ResultDataDto(CODE_SUCCESS, "操作成功"); } public ResultDataDto() { super(); } public ResultDataDto(String code, String message) { super(); this.code = code; this.message = message; } public ResultDataDto(String message) { super(); this.code = CODE_SUCCESS; this.message = message; } /** * 返回单个实体 */ public<T extends BaseEntity> ResultDataDto(T entity) { super(); this.code = CODE_SUCCESS; this.datas = entity; } /** * 返回集合类型 */ public ResultDataDto(List<? extends BaseEntity> list) { super(); this.code = CODE_SUCCESS; this.datas = list; } /** * 返回Map集合类型 */ public ResultDataDto(Map<String, Object> map) { super(); this.code = CODE_SUCCESS; this.datas = map; } /** * 返回分页集合 */ public<T extends BaseEntity> ResultDataDto(List<T> list, FlexiPageDto flexiPageDto) { super(); this.code = CODE_SUCCESS; this.datas = list; this.flexiPageDto = flexiPageDto; } /** * 500-业务逻辑错误 */ public ResultDataDto(RuntimeServiceException rex) { super(); this.code = CODE_ERROR_SERVICE; this.message = rex.getMessage(); } /** * 501-功能不完善,无对应方法 */ public ResultDataDto(RuntimeFunctionException rex) { super(); this.code = CODE_ERROR_FUNCTION; this.message = rex.getMessage(); } /** * 502-网络异常 */ public ResultDataDto(RuntimeWebException rex) { super(); this.code = CODE_ERROR_WEB; this.message = rex.getMessage(); } /** * 503-未知其它 */ public ResultDataDto(RuntimeOtherException rex) { super(); this.code = CODE_ERROR_OTHER; this.message = rex.getMessage(); } /** * 异常 */ public ResultDataDto(Exception ex) { super(); this.code = CODE_ERROR_OTHER; this.message = getErrorMessage(ex); ex.printStackTrace(); } /** * 运行时异常 */ public ResultDataDto(RuntimeException rex) { super(); this.code = CODE_ERROR_OTHER; this.message = rex.getMessage(); } /** * 运行时异常 */ public ResultDataDto(Throwable tx) { super(); this.code = CODE_ERROR_OTHER; this.message = tx.getMessage(); } /** * 结果编码 */ @XmlElement(name="code") private String code; /** * 消息 */ private String message; /** * 结果数据,单个实体 或 List<T> */ private Object datas; /** * 分页数据 */ private FlexiPageDto flexiPageDto; private static String getErrorMessage(Exception ex) { if (ex instanceof ArithmeticException) { return "系统异常:计算错误"; } if (ex instanceof NullPointerException) { return "系统异常:输入错误,缺少输入值"; } if (ex instanceof ClassCastException) { return "系统异常:类型转换错误"; } if (ex instanceof NegativeArraySizeException) { return "系统异常:集合负数"; } if (ex instanceof ArrayIndexOutOfBoundsException) { return "系统异常:集合超出范围"; } if (ex instanceof FileNotFoundException) { return "系统异常:文件未找到"; } if (ex instanceof NumberFormatException) { return "系统异常:输入数字错误"; } if (ex instanceof SQLException) { return "系统异常:数据库异常"; } if (ex instanceof IOException) { return "系统异常:文件读写错误"; } if (ex instanceof NoSuchMethodException) { return "系统异常:方法找不到"; } return ex.getMessage(); } // -------------------------- getter and setter ----------------------------- public String getCode() { return code; } public ResultDataDto setCode(String code) { this.code = code; return this; } public Object getDatas() { return datas; } public ResultDataDto setDatas(Object datas) { this.datas = datas; return this; } public String getMessage() { return message; } public ResultDataDto setMessage(String message) { this.message = message; return this; } public FlexiPageDto getFlexiPageDto() { return flexiPageDto; } public ResultDataDto setFlexiPageDto(FlexiPageDto flexiPageDto) { this.flexiPageDto = flexiPageDto; return this; } }
分页Dto传输对象,FlexiPageDto:
src/main/java/com/training/core/dto/FlexiPageDto.java
package com.training.core.dto; public class FlexiPageDto { public static final Integer MAX_PAGE_SIZE=3000; public static final Integer SHORT_PAGE_SIZE=5; public FlexiPageDto() { super(); } public FlexiPageDto(Integer page, Integer rp) { super(); this.page = page; this.rp = rp; } public FlexiPageDto(Integer page, Integer rp, String sortName) { super(); this.page = page; this.rp = rp; this.sortName = sortName; } public FlexiPageDto(Integer page, Integer rp, String sortName, String sortOrder) { super(); this.page = page; this.rp = rp; this.sortName = sortName; this.sortOrder = sortOrder; } public static FlexiPageDto createMaxPageDto(){ FlexiPageDto flexiPageDto=new FlexiPageDto(); flexiPageDto.setRp(MAX_PAGE_SIZE).setPage(1); return flexiPageDto; } public static FlexiPageDto generateFlexiPageDto(Integer page, Integer rp, String orderBy) { FlexiPageDto flexiPageDto = new FlexiPageDto(page, rp); if (null != orderBy && "" != orderBy.trim()) { String[] orderBys = orderBy.split("_"); flexiPageDto.setSortName(orderBys[0]); flexiPageDto.setSortOrder(orderBys[1]); } return flexiPageDto; } /** * 当前页 */ private Integer page; /** * 每页显示,默认:10 */ private Integer rp = 10; /** * 总记录数 */ private Integer rowCount; /** * 排序字段 */ private String sortName; /** * 排序(asc/desc) */ private String sortOrder = "desc"; public static final String SORTORDER_ACS = "asc"; /** * 数据开始坐标,Mysql从0开始 */ public Integer getOffset(){ return (this.getPage()-1)*this.getRp(); } /** * 总页数 */ public Integer getTotalPage() { if (null == rowCount) { return 0; } int totalPage = (rowCount / rp); int remainder = rowCount % rp; if (rowCount > 0 && totalPage == 0) { totalPage = 1; return totalPage; } if (remainder > 0) { totalPage++; return totalPage; } return totalPage; } // -------------------------- getter and setter ----------------------------- public Integer getRp() { return rp; } public FlexiPageDto setRp(Integer rp) { this.rp = rp; return this; } public Integer getPage() { return page; } public FlexiPageDto setPage(Integer page) { this.page = page; return this; } public String getSortName() { return sortName; } public FlexiPageDto setSortName(String sortName) { this.sortName = sortName; return this; } public String getSortOrder() { return sortOrder; } public FlexiPageDto setSortOrder(String sortOrder) { this.sortOrder = sortOrder; return this; } public Integer getRowCount() { return rowCount; } public FlexiPageDto setRowCount(Integer rowCount) { this.rowCount = rowCount; return this; } public String getSortString(){ if (null == sortName) { return null; } String[] fields = this.getSortName().split("_"); String[] fieldsorts = this.getSortOrder().split("_"); if(fields.length!=fieldsorts.length){ throw new RuntimeException("排序规则不一致"); } String sql = ""; for(int index=0;index<fields.length;index++){ sql = sql+" "+fields[index]+" "+fieldsorts[index]; } return sql; } }
自定义异常:
src/main/java/com/training/core/exception/RuntimeFunctionException.java
src/main/java/com/training/core/exception/RuntimeOtherException.java
src/main/java/com/training/core/exception/RuntimeServiceException.java
src/main/java/com/training/core/exception/RuntimeWebException.java
集成Runtime Exception,其余略。
package com.training.core.exception; @SuppressWarnings("serial") public class RuntimeFunctionException extends RuntimeException { public RuntimeFunctionException() { super(); } public RuntimeFunctionException(String message, Throwable cause) { super(message, cause); } public RuntimeFunctionException(String message) { super(message); } public RuntimeFunctionException(Throwable cause) { super(cause); } }