MyBatis分页插件的使用和抽象对象之间的转换关系

MyBatis分页插件的使用和抽象对象之间的转换关系

抽象POJO、BO、VO对象之间的转换关系

各种对象关系转换.png

例:产品管理中部分操作,当需要返回的信息跟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>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,087评论 18 139
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,266评论 0 4
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,301评论 6 344
  • 我是在老家读完初中,没有上高中,虽然自己高中也是能考上的,但是没有去上,跑到广州来读中专了,我的第一个同桌不是她,...
    huangjiajia阅读 269评论 0 0
  • 首先问个简单的问题:“钱和小孩哪个重要?只选其一。”我想百分之百的会选择小孩吧!但我告诉你:错!现实中的答案是钱。...
    番石榴阅读 393评论 4 3