MyBatis分页插件的使用和抽象对象之间的转换关系
抽象POJO、BO、VO对象之间的转换关系
例:产品管理中部分操作,当需要返回的信息跟pojo不一样时,创建一个新的vo(value Ojbect)对象,再将其组装返回个前端。
POJO:
Product:
public class Product {
private Integer id;
private Integer categoryId;
private String name;
private String subtitle;
private String mainImage;
private String subImages;
private String detail;
private BigDecimal price;
private Integer stock;
private Integer status;
private Date createTime;
private Date updateTime;
}
VO(value Object):
ProductDetailVo:
public class ProductDetailVo {
private Integer id;
private Integer categoryId;
private String name;
private String subtitle;
private String mainImage;
private String subImages;
private String detail;
private BigDecimal price;
private Integer stock;
private Integer status;
private String createTime;
private String updateTime;
private String imageHost;
private Integer parentCategoryId;
}
ProductListVo:
public class ProductListVo {
private Integer id;
private Integer categoryId;
private String name;
private String subtitle;
private String mainImage;
private BigDecimal price;
private Integer status;
private String imageHost;
}
ProductManageController:
/**
* 获取产品详情
* @param session
* @param productId
* @return
*/
@RequestMapping("detail.do")
@ResponseBody
public ServerResponse getDetail(HttpSession session, Integer productId){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.manageProductDetail(productId);
}else {
return ServerResponse.createByErrorMessage("无权限操作");
}
}
/**
* 获取产品列表
* @param session
* @param pageNum 第几页
* @param pageSize 每页显示多少条
* @return
*/
@RequestMapping("list.do")
@ResponseBody
public ServerResponse getList(HttpSession session,
@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.getProductList(pageNum,pageSize);
}else {
return ServerResponse.createByErrorMessage("无权限操作");
}
}
/**
* 产品搜索
* @param session
* @param productName
* @param productId
* @param pageNum
* @param pageSize
* @return
*/
@RequestMapping("search.do")
@ResponseBody
public ServerResponse productSearch(HttpSession session,String productName,Integer productId,
@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.searchProduct(productName,productId,pageNum,pageSize);
}else {
return ServerResponse.createByErrorMessage("无权限操作");
}
}
serviceImpl:
@Override
public ServerResponse<ProductDetailVo> manageProductDetail(Integer productId){
if(productId == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
ResponseCode.ILLEGAL_ARGUMENT.getDesc());
}
Product product = productMapper.selectByPrimaryKey(productId);
if(product == null){
return ServerResponse.createByErrorMessage("产品已下架或者删除");
}
//VO对象:value Object
//pojo--->bo(business object)--->vo(view object)
ProductDetailVo productDetailVo = assembleProductDetailVo(product);
return ServerResponse.createBySuccess(productDetailVo);
}
private ProductDetailVo assembleProductDetailVo(Product product){
ProductDetailVo productDetailVo = new ProductDetailVo();
productDetailVo.setId(product.getId());
productDetailVo.setSubtitle(product.getSubtitle());
productDetailVo.setPrice(product.getPrice());
productDetailVo.setMainImage(product.getMainImage());
productDetailVo.setSubImages(product.getSubImages());
productDetailVo.setCategoryId(product.getCategoryId());
productDetailVo.setDetail(product.getDetail());
productDetailVo.setName(product.getName());
productDetailVo.setStatus(product.getStatus());
productDetailVo.setStock(product.getStock());
//imageHost:从配置文件中获取,不需要把url硬编码到项目中,如果图片服务器修改了,只需要修改配置文件
productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
//parentCategoryId
Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
if(category == null){
//默认根节点
productDetailVo.setParentCategoryId(0);
}else {
productDetailVo.setParentCategoryId(category.getParentId());
}
//createTime
productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
//updateTime
productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
return productDetailVo;
}
pageHelper的使用方法:
(1)记录起始页startPage
(2)填充sql查询逻辑
(3)收尾
@Override
public ServerResponse<PageInfo> getProductList(int pageNum,int pageSize){
//1.记录起始页startPage
PageHelper.startPage(pageNum,pageSize);
//2.填充sql查询逻辑
List<Product> productList = productMapper.selectList();
List<ProductListVo> productListVoList = Lists.newArrayList();
for(Product productItem : productList){
ProductListVo productListVo = assembleProductListVo(productItem);
productListVoList.add(productListVo);
}
//3.收尾
PageInfo pageResult = new PageInfo(productList);
//把list重置
pageResult.setList(productListVoList);
return ServerResponse.createBySuccess(pageResult);
}
/**
* 组装productListVo
* @param product
* @return
*/
private ProductListVo assembleProductListVo(Product product){
ProductListVo productListVo = new ProductListVo();
productListVo.setId(product.getId());
productListVo.setCategoryId(product.getCategoryId());
productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
productListVo.setMainImage(product.getMainImage());
productListVo.setPrice(product.getPrice());
productListVo.setSubtitle(product.getSubtitle());
productListVo.setStatus(product.getStatus());
return productListVo;
}
mybatis.xml:
<select id="selectList" resultMap="BaseResultMap" >
SELECT <include refid="Base_Column_List"/>
FROM mmall_product
ORDER BY id ASC
</select>
<select id="selectByNameAndProductId" resultMap="BaseResultMap" parameterType="map">
SELECT <include refid="Base_Column_List" />
FROM mmall_product
<where>
<if test="productName!=null">
AND name LIKE #{productName}
</if>
<if test="productId!=null">
AND id=#{productId}
</if>
</where>
</select>
为了防止硬编码,在获取图片url时,使用了配置文件:
hcxmall.properties:
ftp.server.ip=
ftp.user=hcxmallftp
ftp.pass=ftppassword
#搭建的图片服务器的前缀
ftp.server.http.prefix=http://img.happymmall.com/
alipay.callback.url=http://www.happymmall.com/order/alipay_callback.do
password.salt = geelysdafaqj23ou89ZXcj@#$@#$#@KJdjklj;D../dSF.,
因为配置文件里的东西会在多处用到,每一次都要读取,所以封装了一个使用流读取配置文件的工具类PropertiesUtil:
package com.hcxmall.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* 配置文件工具类
* @author HCX
* @create 2017 - 11 - 15 18:28
*/
public class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
//在tomcat启动时读取里面的配置:使用静态代码块
//执行顺序:静态代码块(在类被加载的时候执行且仅执行一次)>普通代码块>构造代码块
//静态代码块:一般用于初始化静态变量。
static{
String fileName = "hcxmall.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常",e);
}
}
/**
* 获取hcxmall.propeties文件中的信息:通过key获取value
* @param key
* @return
*/
public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}
public static String getProperty(String key,String defaultValue){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}
}
在进行时间的转换时,也可使用工具类,其中,应用joda-time实现:
DateTimeUtil:
package com.hcxmall.util;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
/**
* 时间转换工具类
*
* @author HCX
* @create 2017 - 11 - 15 18:57
*/
public class DateTimeUtil {
public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
//joda-time
public static Date strToDate(String dateTimeStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
//strToDate("2010-01-01 11:11:11","yyyy-MM-dd HH:mm:ss"); Fri Jan 01 11:11:11 CST 2010
}
public static String dateToStr(Date date){
if(date == null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(STANDARD_FORMAT);
//dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"); 2017-11-15 19:15:50
}
/**
* 字符串转date
* @param dateTimeStr
* @param formatStr
* @return
*/
public static Date strToDate(String dateTimeStr,String formatStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
//strToDate("2010-01-01 11:11:11","yyyy-MM-dd HH:mm:ss"); Fri Jan 01 11:11:11 CST 2010
}
/**
* date转字符串
* @param date
* @param formatStr 要转化成的格式 例:yyyy-MM-dd HH:mm:ss
* @return
*/
public static String dateToStr(Date date,String formatStr){
if(date == null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(formatStr);
//dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"); 2017-11-15 19:15:50
}
}
在上面实现属性的拷贝时,频繁的编写get()和set()方法,此时,也可以使用工具类来完成
pom.xml:
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
<!--时间处理jar-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>