目前,我们的查询会添加各种限制,以确保结果被视为有效或有效。这些限制用于多个地方/查询,因此设置方法类似于
public Criteria addStandardCriteria(Criteria criteria, ...) {
// Add restrictions, create aliases based on parameters
// and other non-trivial logic
criteria.add(...);
return criteria;
}
到目前为止,此工作正常,但现在需要使用DetachedCriteria将此标准条件添加到子查询中。有没有办法修改此方法以接受Criteria或DetachedCriteria或更好的方法来添加限制?
答案 0 :(得分:1)
我最终重写了查询,所以这不再是一个问题,但在此之前我创建了这个似乎有用的课程,但你的里程可能会有所不同:
public class CriteriaContainer implements Serializable {
private static final long serialVersionUID = 1L;
private Criteria criteria = null;
private DetachedCriteria detachedCriteria = null;
public CriteriaContainer(Criteria criteria) {
this.criteria = criteria;
this.detachedCriteria = null;
}
public CriteriaContainer(DetachedCriteria detachedCriteria) {
this.detachedCriteria = detachedCriteria;
this.criteria = null;
}
/**
* @param eq
* @return
*/
public CriteriaContainer add(final Criterion eq) {
if (criteria != null) {
criteria.add(eq);
} else if (detachedCriteria != null) {
detachedCriteria.add(eq);
}
return this;
}
/**
* @return the criteria
*/
public Criteria getCriteria() {
return criteria;
}
/**
* @return the detachedCriteria
*/
public DetachedCriteria getDetachedCriteria() {
return detachedCriteria;
}
/**
* @param associationPath
* @param alias
* @return
*/
public CriteriaContainer createAlias(final String associationPath, final String alias) {
if (criteria != null) {
criteria.createAlias(associationPath, alias);
} else if (detachedCriteria != null) {
detachedCriteria.createAlias(associationPath, alias);
}
return this;
}
/**
* @param distinctRootEntity
* @return
*/
public CriteriaContainer setResultTransformer(final ResultTransformer transformer) {
if (criteria != null) {
criteria.setResultTransformer(transformer);
} else if (detachedCriteria != null) {
detachedCriteria.setResultTransformer(transformer);
}
return this;
}
}
criteria = addBasicCriteria(new CriteriaContainer(criteria), ...).getCriteria()
detachedCriteria = addBasicCriteria(new CriteriaContainer(detachedCriteria), ...).getDetachedCriteria()