View Javadoc

1   /*
2    * Copyright 2007-2008 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.core.jpa.criteria;
17  
18  import javax.persistence.EntityManager;
19  import javax.persistence.Query;
20  
21  
22  /**
23   * @author Kuali Rice Team (rice.collab@kuali.org)
24   */
25  public class QueryByCriteria {
26  
27      private EntityManager entityManager;
28      private Criteria criteria;
29      private QueryByCriteriaType type;
30      
31      public enum QueryByCriteriaType {SELECT, DELETE}
32      
33      public QueryByCriteria(EntityManager entityManager, Criteria criteria) {
34          this(entityManager, criteria, QueryByCriteriaType.SELECT);
35      }
36  
37      public QueryByCriteria(EntityManager entityManager, Criteria criteria, QueryByCriteriaType type) {
38          this.entityManager = entityManager;
39          this.criteria = criteria;
40          this.type = type;
41      }
42  
43      public Query toQuery() {
44          Query query = entityManager.createQuery(criteria.toQuery(type));
45          if (criteria.getSearchLimit() != null) {
46              query.setMaxResults(criteria.getSearchLimit());        	
47          }
48          criteria.prepareParameters(query);
49          return query;
50      }
51      
52      public Query toCountQuery() {
53          Query query = entityManager.createQuery(criteria.toCountQuery());
54          if (criteria.getSearchLimit() != null) {
55              query.setMaxResults(criteria.getSearchLimit());        	
56          }
57          criteria.prepareParameters(query);
58          return query;
59      }
60  
61  }