| 1 | /* |
| 2 | * Copyright 2006-2013 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 | package org.springframework.batch.item.database; |
| 17 | |
| 18 | import java.util.Map; |
| 19 | |
| 20 | import org.hibernate.ScrollableResults; |
| 21 | import org.hibernate.Session; |
| 22 | import org.hibernate.SessionFactory; |
| 23 | import org.hibernate.StatelessSession; |
| 24 | import org.springframework.batch.item.ExecutionContext; |
| 25 | import org.springframework.batch.item.ItemStreamReader; |
| 26 | import org.springframework.batch.item.ItemStreamException; |
| 27 | import org.springframework.batch.item.database.orm.HibernateQueryProvider; |
| 28 | import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader; |
| 29 | import org.springframework.beans.factory.InitializingBean; |
| 30 | import org.springframework.util.Assert; |
| 31 | import org.springframework.util.ClassUtils; |
| 32 | |
| 33 | /** |
| 34 | * {@link ItemStreamReader} for reading database records built on top of Hibernate. It |
| 35 | * executes the HQL query when initialized iterates over the result set as |
| 36 | * {@link #read()} method is called, returning an object corresponding to |
| 37 | * current row. The query can be set directly using |
| 38 | * {@link #setQueryString(String)}, a named query can be used by |
| 39 | * {@link #setQueryName(String)}, or a query provider strategy can be supplied |
| 40 | * via {@link #setQueryProvider(HibernateQueryProvider)}. |
| 41 | * |
| 42 | * |
| 43 | * <p> |
| 44 | * The reader can be configured to use either {@link StatelessSession} |
| 45 | * sufficient for simple mappings without the need to cascade to associated |
| 46 | * objects or standard hibernate {@link Session} for more advanced mappings or |
| 47 | * when caching is desired. When stateful session is used it will be cleared in |
| 48 | * the {@link #update(ExecutionContext)} method without being flushed (no data |
| 49 | * modifications are expected). |
| 50 | * </p> |
| 51 | * |
| 52 | * The implementation is <b>not</b> thread-safe. |
| 53 | * |
| 54 | * @author Robert Kasanicky |
| 55 | * @author Dave Syer |
| 56 | */ |
| 57 | public class HibernateCursorItemReader<T> extends AbstractItemCountingItemStreamItemReader<T> |
| 58 | implements InitializingBean { |
| 59 | |
| 60 | private HibernateItemReaderHelper<T> helper = new HibernateItemReaderHelper<T>(); |
| 61 | |
| 62 | public HibernateCursorItemReader() { |
| 63 | setName(ClassUtils.getShortName(HibernateCursorItemReader.class)); |
| 64 | } |
| 65 | |
| 66 | private ScrollableResults cursor; |
| 67 | |
| 68 | private boolean initialized = false; |
| 69 | |
| 70 | private int fetchSize; |
| 71 | |
| 72 | private Map<String, Object> parameterValues; |
| 73 | |
| 74 | @Override |
| 75 | public void afterPropertiesSet() throws Exception { |
| 76 | Assert.state(fetchSize >= 0, "fetchSize must not be negative"); |
| 77 | helper.afterPropertiesSet(); |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * The parameter values to apply to a query (map of name:value). |
| 82 | * |
| 83 | * @param parameterValues the parameter values to set |
| 84 | */ |
| 85 | public void setParameterValues(Map<String, Object> parameterValues) { |
| 86 | this.parameterValues = parameterValues; |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * A query name for an externalized query. Either this or the { |
| 91 | * {@link #setQueryString(String) query string} or the { |
| 92 | * {@link #setQueryProvider(HibernateQueryProvider) query provider} should |
| 93 | * be set. |
| 94 | * |
| 95 | * @param queryName name of a hibernate named query |
| 96 | */ |
| 97 | public void setQueryName(String queryName) { |
| 98 | helper.setQueryName(queryName); |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Fetch size used internally by Hibernate to limit amount of data fetched |
| 103 | * from database per round trip. |
| 104 | * |
| 105 | * @param fetchSize the fetch size to pass down to Hibernate |
| 106 | */ |
| 107 | public void setFetchSize(int fetchSize) { |
| 108 | this.fetchSize = fetchSize; |
| 109 | } |
| 110 | |
| 111 | /** |
| 112 | * A query provider. Either this or the {{@link #setQueryString(String) |
| 113 | * query string} or the {{@link #setQueryName(String) query name} should be |
| 114 | * set. |
| 115 | * |
| 116 | * @param queryProvider Hibernate query provider |
| 117 | */ |
| 118 | public void setQueryProvider(HibernateQueryProvider queryProvider) { |
| 119 | helper.setQueryProvider(queryProvider); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * A query string in HQL. Either this or the { |
| 124 | * {@link #setQueryProvider(HibernateQueryProvider) query provider} or the { |
| 125 | * {@link #setQueryName(String) query name} should be set. |
| 126 | * |
| 127 | * @param queryString HQL query string |
| 128 | */ |
| 129 | public void setQueryString(String queryString) { |
| 130 | helper.setQueryString(queryString); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * The Hibernate SessionFactory to use the create a session. |
| 135 | * |
| 136 | * @param sessionFactory the {@link SessionFactory} to set |
| 137 | */ |
| 138 | public void setSessionFactory(SessionFactory sessionFactory) { |
| 139 | helper.setSessionFactory(sessionFactory); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Can be set only in uninitialized state. |
| 144 | * |
| 145 | * @param useStatelessSession <code>true</code> to use |
| 146 | * {@link StatelessSession} <code>false</code> to use standard hibernate |
| 147 | * {@link Session} |
| 148 | */ |
| 149 | public void setUseStatelessSession(boolean useStatelessSession) { |
| 150 | helper.setUseStatelessSession(useStatelessSession); |
| 151 | } |
| 152 | |
| 153 | @Override |
| 154 | protected T doRead() throws Exception { |
| 155 | if (cursor.next()) { |
| 156 | Object[] data = cursor.get(); |
| 157 | |
| 158 | if (data.length > 1) { |
| 159 | // If there are multiple items this must be a projection |
| 160 | // and T is an array type. |
| 161 | @SuppressWarnings("unchecked") |
| 162 | T item = (T) data; |
| 163 | return item; |
| 164 | } |
| 165 | else { |
| 166 | // Assume if there is only one item that it is the data the user |
| 167 | // wants. |
| 168 | // If there is only one item this is going to be a nasty shock |
| 169 | // if T is an array type but there's not much else we can do... |
| 170 | @SuppressWarnings("unchecked") |
| 171 | T item = (T) data[0]; |
| 172 | return item; |
| 173 | } |
| 174 | |
| 175 | } |
| 176 | return null; |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Open hibernate session and create a forward-only cursor for the query. |
| 181 | */ |
| 182 | @Override |
| 183 | protected void doOpen() throws Exception { |
| 184 | Assert.state(!initialized, "Cannot open an already opened ItemReader, call close first"); |
| 185 | cursor = helper.getForwardOnlyCursor(fetchSize, parameterValues); |
| 186 | initialized = true; |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * Update the context and clear the session if stateful. |
| 191 | * |
| 192 | * @param executionContext the current {@link ExecutionContext} |
| 193 | * @throws ItemStreamException if there is a problem |
| 194 | */ |
| 195 | @Override |
| 196 | public void update(ExecutionContext executionContext) throws ItemStreamException { |
| 197 | super.update(executionContext); |
| 198 | helper.clear(); |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * Wind forward through the result set to the item requested. Also clears |
| 203 | * the session every now and then (if stateful) to avoid memory problems. |
| 204 | * The frequency of session clearing is the larger of the fetch size (if |
| 205 | * set) and 100. |
| 206 | * |
| 207 | * @param itemIndex the first item to read |
| 208 | * @throws Exception if there is a problem |
| 209 | * @see AbstractItemCountingItemStreamItemReader#jumpToItem(int) |
| 210 | */ |
| 211 | @Override |
| 212 | protected void jumpToItem(int itemIndex) throws Exception { |
| 213 | int flushSize = Math.max(fetchSize, 100); |
| 214 | helper.jumpToItem(cursor, itemIndex, flushSize); |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Close the cursor and hibernate session. |
| 219 | */ |
| 220 | @Override |
| 221 | protected void doClose() throws Exception { |
| 222 | |
| 223 | initialized = false; |
| 224 | |
| 225 | if (cursor != null) { |
| 226 | cursor.close(); |
| 227 | } |
| 228 | |
| 229 | helper.close(); |
| 230 | |
| 231 | } |
| 232 | } |