应用实例截图:
前台提交数据,用户可以有选择的进行填写
好吧~ 还是直接上代码吧.....
1.用户接收前台页面提交的数据DTO,该类用户接收商品Commodity的信息
- public class CommodityDTO {
- private Integer categoryId; // 一级分类id
- private Integer subCategoryId; // 二级分类id
- private String name; // 商品名称
- private Float fromPrice; // 起始价格
- private Float toPrice;
- private Integer fromSalesVolume; // 起始销售量
- private Integer toSalesVolume;
- // 此处省略set/get方法
- }
2.DAOImpl层
- @Override
- public List<Commodity> queryByRestrictions(CommodityDTO commodityDTO, int pageOffset, int pageSize) {
- Session session = this.getSession();
- DetachedCriteria dc = myDetachedCriteria(commodityDTO);
- List<Commodity> commodities = dc.getExecutableCriteria(session)
- .setFirstResult(pageOffset).setMaxResults(pageSize).list();
- return commodities;
- }
- /**
- * 添加动态条件
- *
- * @param commodityDTO
- * @return
- */
- private DetachedCriteria myDetachedCriteria(CommodityDTO commodityDTO) {
- DetachedCriteria dc = DetachedCriteria.forClass(Commodity.class);
- Integer categoryId = commodityDTO.getCategoryId();
- Integer subCategoryId = commodityDTO.getSubCategoryId();
- String name = commodityDTO.getName();
- Float fromPrice = commodityDTO.getFromPrice();
- Float toPrice = commodityDTO.getToPrice();
- Integer fromSalesVolume = commodityDTO.getFromSalesVolume();
- Integer toSalesVolume = commodityDTO.getToSalesVolume();
- if (categoryId != null && categoryId.intValue() > 0) {
- dc.add(Restrictions.eq("category.id", categoryId));
- }
- if (subCategoryId != null && subCategoryId.intValue() > 0) {
- dc.add(Restrictions.eq("subCategory.id", subCategoryId));
- }
- if (name != null && !"".equals(name.trim())) {
- dc.add(Restrictions.eq("name", name));
- }
- if (fromPrice != null && fromPrice.intValue() > 0) {
- dc.add(Restrictions.ge("price", fromPrice));
- }
- if (toPrice != null && toPrice.intValue() > 0) {
- dc.add(Restrictions.le("price", toPrice));
- }
- if (fromSalesVolume != null && fromSalesVolume.intValue() > 0) {
- dc.add(Restrictions.ge("salesVolume", fromSalesVolume));
- }
- if (toSalesVolume != null && toSalesVolume.intValue() > 0) {
- dc.add(Restrictions.le("salesVolume", toSalesVolume));
- }
- return dc;
- }