我使用org.hibernate.criterion.Example.create从实体对象创建查询。一切都很好,但是使用这个方法,SQL只能在限制之间使用AND子句创建。
是否可以使用org.hibernate.criterion.Example.create但带OR子句?
发布于 2014-07-24 02:42:08
简单来说,答案是否定的,你不能这样做,但是你可以实现一个OrExample,这很容易,只检查Example的源代码并为or修改and (参见源码第329行)。由于这些方法是受保护的,所以您可以扩展它并仅覆盖所需的内容。
就像这样:
public class OrExample extends org.hibernate.criterion.Example {
@Override
protected void appendPropertyCondition(
String propertyName,
Object propertyValue,
Criteria criteria,
CriteriaQuery cq,
StringBuffer buf)
throws HibernateException {
Criterion crit;
if ( propertyValue!=null ) {
boolean isString = propertyValue instanceof String;
if ( isLikeEnabled && isString ) {
crit = new LikeExpression(
propertyName,
( String ) propertyValue,
matchMode,
escapeCharacter,
isIgnoreCaseEnabled
);
}
else {
crit = new SimpleExpression( propertyName, propertyValue, "=", isIgnoreCaseEnabled && isString );
}
}
else {
crit = new NullExpression(propertyName);
}
String critCondition = crit.toSqlString(criteria, cq);
if ( buf.length()>1 && critCondition.trim().length()>0 ) buf.append(" or ");
buf.append(critCondition);
}查看or而不是原始的and。
发布于 2014-07-24 02:29:45
可以,停那儿吧
session.createCriteria(Person.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", "James")) .add(Restrictions.eq("age", 20)) );在上面的示例中,类Person将具有属性name和age,而您将选择具有name = "James“或age = 20的人。
发布于 2014-07-24 02:44:21
SO中的一篇旧文章可能会有所帮助:Hibernate条件限制和/或组合
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq("A", "X"),
Restrictions.in("B", Arrays.asList("X","Y")));
Criterion rest2= Restrictions.and(Restrictions.eq("A", "Y"),
Restrictions.eq("B", "Z"));
criteria.add(Restrictions.or(rest1, rest2));https://stackoverflow.com/questions/24924112
复制相似问题