1 | /* |
2 | * Copyright 2006-2008 the original author or authors. |
3 | * |
4 | * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 |
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 | |
17 | package org.springframework.batch.item.database.orm; |
18 | |
19 | import org.hibernate.Query; |
20 | import org.hibernate.SQLQuery; |
21 | import org.springframework.util.Assert; |
22 | import org.springframework.util.StringUtils; |
23 | |
24 | /** |
25 | * <p> |
26 | * This query provider creates Hibernate {@link Query}s from injected native SQL |
27 | * queries. This is useful if there is a need to utilize database-specific |
28 | * features such as query hints, the CONNECT keyword in Oracle, etc. |
29 | * </p> |
30 | * |
31 | * @author Anatoly Polinsky |
32 | * |
33 | * @param <E> entity returned by executing the query |
34 | */ |
35 | public class HibernateNativeQueryProvider<E> extends AbstractHibernateQueryProvider { |
36 | |
37 | private String sqlQuery; |
38 | |
39 | private Class<E> entityClass; |
40 | |
41 | /** |
42 | * <p> |
43 | * Create an {@link SQLQuery} from the session provided (preferring |
44 | * stateless if both are available). |
45 | * </p> |
46 | */ |
47 | @Override |
48 | public SQLQuery createQuery() { |
49 | |
50 | if (isStatelessSession()) { |
51 | return getStatelessSession().createSQLQuery(sqlQuery).addEntity(entityClass); |
52 | } |
53 | else { |
54 | return getStatefulSession().createSQLQuery(sqlQuery).addEntity(entityClass); |
55 | } |
56 | } |
57 | |
58 | public void setSqlQuery(String sqlQuery) { |
59 | this.sqlQuery = sqlQuery; |
60 | } |
61 | |
62 | public void setEntityClass(Class<E> entityClazz) { |
63 | this.entityClass = entityClazz; |
64 | } |
65 | |
66 | public void afterPropertiesSet() throws Exception { |
67 | Assert.isTrue(StringUtils.hasText(sqlQuery), "Native SQL query cannot be empty"); |
68 | Assert.notNull(entityClass, "Entity class cannot be NULL"); |
69 | } |
70 | } |