我有一大块java代码,它硬编码了一个看起来像这样的hibernate析取查询
session = HibernateUtils.beginTransaction("outpatient");
Criteria criteria = session.createCriteria(AugmentToken.class);
session.beginTransaction();
if (type == Constants.ICD9CPT) {
criteria.add(Restrictions.disjunction()
.add(Restrictions.eq("codeType", "d"))
.add(Restrictions.eq("codeType", "p"))
.add(Restrictions.eq("codeType", "c")));
} else if (type == Constants.EM) {
criteria.add(Restrictions.disjunction()
.add(Restrictions.eq("codeType", "eros"))
.add(Restrictions.eq("codeType", "ehpi"))
.add(Restrictions.eq("codeType", "epe")));
}
但这不是非常优雅的代码。我想做的是将代码类型数组传递给方法,并动态构造析取标准。我查看的每个网站都提供了与上面类似的析取查询示例,但这对我不起作用,因为我不想对条件限制的构造进行硬编码,因为代码类型的数量可能会有所不同。
我该怎么做?
谢谢,
埃利奥特
最佳答案
我想我已经明白了这一点。您将析取创建为变量,然后按顺序添加到它。
具体来说:
String [] codeTypes = new String[3];
codeTyes[0]="d";
codeTypes[1]="p";
codetypes[2]="c";
/* note the above would normally be passed into the method containing the code below */
Criteria criteria = session.createCriteria(AugmentToken.class);
session.beginTransaction();
Disjunction disjunction = Restrictions.disjunction();
for (int x = 0; x < codeTypes.length; x++ ) {
disjucntion.add(Restrictions.eq("codeType",codeTypes[x]);
}
criteria.add(disjunction);
我在第 214 页的《开始 hibernate 》中找到了答案。可从 books.google.com 访问该书。
关于java - 以编程方式创建 Hibernate 析取查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657283/