使用子条件创建动态休眠条件查询
我有一个 Java 类,其中一些字段用 @SearchCriteria(criteria = "class1.class2.field") 注释。注释内的 criteria
参数意味着对于类,该字段应设置为休眠条件,这意味着,如果字段标记为例如:
@SearchCriteria(criteria = "class1.class2.field")
private String value;
我想动态创建休眠条件,看起来像
DetachedCriteria hibernateCriteria = forClass(Class.class);
hibernateCriteria.createCriteria("class1").createCriteria("class2").add(eq("field", value));
问题是我无法设置已经添加了另一个标准,这意味着我应该检查注释 criteria
选项。
switch (annotationCriteria.length - 1) {
case 0:
hibernateCriteria.add(isNull(annotationCriteria[0]));
case 1:
hibernateCriteria.createCriteria(annotationCriteria[0]).add( Restrictions.isNull(annotationCriteria[annotationCriteria.length - 1]));
case 2: hibernateCriteria.createCriteria(annotationCriteria[0]).createCriteria(annotationCriteria[1]).add( Restrictions.isNull(annotationCriteria[annotationCriteria.length - 1]));
}
我想删除这个“开关”。可以通过(我现在不这样做)获得已经添加的标准,例如通过“名称”,并为其添加新的子标准。
I have a Java class which has some field annotated with @SearchCriteria(criteria = "class1.class2.field")
. criteria
parameter inside annotation means for with class this field should be set as hibernate criteria, it mean that, if field marked for example:
@SearchCriteria(criteria = "class1.class2.field")
private String value;
I want dynamicly create hibernate criteria with looks like
DetachedCriteria hibernateCriteria = forClass(Class.class);
hibernateCriteria.createCriteria("class1").createCriteria("class2").add(eq("field", value));
Problem is than I can not set another criteria to already added, it mean I should check annotation criteria
option.
switch (annotationCriteria.length - 1) {
case 0:
hibernateCriteria.add(isNull(annotationCriteria[0]));
case 1:
hibernateCriteria.createCriteria(annotationCriteria[0]).add( Restrictions.isNull(annotationCriteria[annotationCriteria.length - 1]));
case 2: hibernateCriteria.createCriteria(annotationCriteria[0]).createCriteria(annotationCriteria[1]).add( Restrictions.isNull(annotationCriteria[annotationCriteria.length - 1]));
}
I want to remove this "swith". It is possible to get already added criteria by, I dont now, for example by "name" and that add new subcriteria for it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是不可能的。 分离条件 API 不 - 对于更好或更坏 - 允许发现,因此您将无法向其询问“现有”标准。
但是,您可以做的是通过关联路径维护您自己的嵌套条件映射。在伪代码中:
No, it's not possible. Detached Criteria API does not - for better or worse - allow for discovery, so you won't be able to ask it for "existing" criteria.
What you can do, however, is maintain your own map of nested criteria by association path. In pseudo-code:
我找到了这个问题的更多“好”解决方案。
首先创建一些 searchCriteria 类,例如:
和自定义注释:
在 DAO 类中:
I find out more "nice" solution for this issue.
First of all create some searchCriteria class, for example:
And custom annotation:
And in DAO class: