现在的位置: 首页 > 综合 > 正文

Hibernate中Criteria的使用

2019年07月16日 ⁄ 综合 ⁄ 共 2149字 ⁄ 字号 评论关闭

如若筛选条件是多个实体类的字段组成的,则可以使用createAlias关联相关的实体类,进行查询。

例如:

@SuppressWarnings("unchecked")
	public PaginationQuery<Product> list(ProductDto productDto, Page page) {
		Criteria criteria = this.getCurrentSession().createCriteria(Product.class,"p")
				.createAlias("document","d").createAlias("customer","c");
		if(productDto != null){
			if(StringUtils.isNotBlank(productDto.getWorkOrdeName())){
				criteria.add(Restrictions.like("p.workOrderName", "%" + productDto.getWorkOrdeName() + "%"));
			}
			if(productDto.getDeployStatus() != null && productDto.getDeployStatus().length != 0){
				List<Integer> statusList = Arrays.asList(productDto.getDeployStatus());
				criteria.add(Restrictions.in("p.status", statusList));
			}
			//关联document
			if(StringUtils.isNotBlank(productDto.getStartTime())){
				try {
					Date startTime = df.parse(productDto.getStartTime());
					criteria.add(Restrictions.ge("d.documentStatTime", startTime));
				} catch (ParseException e) {
					log.error("开始时间转换异常", e);
				}
			}
			if(StringUtils.isNotBlank(productDto.getEndTime())){
				try {
					Date endTime = df.parse(productDto.getEndTime());
					criteria.add(Restrictions.le("d.documentStatTime", endTime));
				} catch (ParseException e) {
					log.error("结束时间转换异常", e);
				}
			}
			//关联customer
			if(StringUtils.isNotBlank(productDto.getCustomerName())){
				criteria.add(Restrictions.eq("c.name", productDto.getCustomerName()));
			}
		}
		if(page != null){
			//总条数
			List<Product> list = criteria.list();
			if(list != null){
	 			int total = list.size();
				page.setRecordCount(total);
			}
			//分页
			criteria.setMaxResults(page.getSize());
			criteria.setFirstResult(page.getIndex()*page.getSize());
		}
		criteria = criteria.addOrder(Order.desc("p.createTime"));
		PaginationQuery<Product> paginationQuery = new PaginationQuery<>();
		paginationQuery.setPlist(criteria.list());
		paginationQuery.setPage(page);
		return paginationQuery;
	}

如若筛选条件就是一个实体类的字段,而查询的字段是多个实体类的字段,则可用setFetchMode进行查询。

例如:

@SuppressWarnings("unchecked")
	public Customer getByName(String name) {
		Criteria criteria = this.getCurrentSession().createCriteria(
				Customer.class);

		if (StringUtils.isNotEmpty(name)) {
			criteria.add(Restrictions.eq("name", name));
		}
		criteria.add(Restrictions.eq("enable", true));
		criteria.setFetchMode("strategies", FetchMode.SELECT);
		List<Customer> customers = criteria.list();
		if (customers != null && customers.size() > 0) {
			return customers.get(0);
		}
		return null;
	}

抱歉!评论已关闭.