001/* 002 * Copyright 2006-2008 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.batch.item.database.orm; 018 019import org.hibernate.query.NativeQuery; 020import org.hibernate.query.Query; 021 022import org.springframework.util.Assert; 023import org.springframework.util.StringUtils; 024 025/** 026 * <p> 027 * This query provider creates Hibernate {@link Query}s from injected native SQL 028 * queries. This is useful if there is a need to utilize database-specific 029 * features such as query hints, the CONNECT keyword in Oracle, etc. 030 * </p> 031 * 032 * @author Anatoly Polinsky 033 * 034 * @param <E> entity returned by executing the query 035 */ 036public class HibernateNativeQueryProvider<E> extends AbstractHibernateQueryProvider<E> { 037 038 private String sqlQuery; 039 040 private Class<E> entityClass; 041 042 /** 043 * <p> 044 * Create an {@link NativeQuery} from the session provided (preferring 045 * stateless if both are available). 046 * </p> 047 */ 048 @Override 049 @SuppressWarnings("unchecked") 050 public NativeQuery<E> createQuery() { 051 052 if (isStatelessSession()) { 053 return getStatelessSession().createNativeQuery(sqlQuery).addEntity(entityClass); 054 } 055 else { 056 return getStatefulSession().createNativeQuery(sqlQuery).addEntity(entityClass); 057 } 058 } 059 060 public void setSqlQuery(String sqlQuery) { 061 this.sqlQuery = sqlQuery; 062 } 063 064 public void setEntityClass(Class<E> entityClazz) { 065 this.entityClass = entityClazz; 066 } 067 068 public void afterPropertiesSet() throws Exception { 069 Assert.isTrue(StringUtils.hasText(sqlQuery), "Native SQL query cannot be empty"); 070 Assert.notNull(entityClass, "Entity class cannot be NULL"); 071 } 072}