以编程方式创建休眠析取查询



我有一大块java代码,它硬编码了一个休眠析取查询,看起来像这样

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页的《开始冬眠》中找到了答案。 这本书可以从 books.google.com 访问。

最新更新