KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > jdbc > core > StatementCreatorUtils


1 /*
2  * Copyright 2002-2007 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.jdbc.core;
18
19 import java.io.StringWriter JavaDoc;
20 import java.math.BigDecimal JavaDoc;
21 import java.sql.PreparedStatement JavaDoc;
22 import java.sql.SQLException JavaDoc;
23 import java.sql.Types JavaDoc;
24 import java.util.Arrays JavaDoc;
25 import java.util.Calendar JavaDoc;
26 import java.util.Collection JavaDoc;
27 import java.util.Iterator JavaDoc;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31
32 import org.springframework.util.ClassUtils;
33
34 /**
35  * Utility methods for PreparedStatementSetter/Creator and CallableStatementCreator
36  * implementations, providing sophisticated parameter management (including support
37  * for LOB values).
38  *
39  * <p>Used by PreparedStatementCreatorFactory and CallableStatementCreatorFactory,
40  * but also available for direct use in custom setter/creator implementations.
41  *
42  * @author Thomas Risberg
43  * @author Juergen Hoeller
44  * @since 1.1
45  * @see PreparedStatementSetter
46  * @see PreparedStatementCreator
47  * @see CallableStatementCreator
48  * @see PreparedStatementCreatorFactory
49  * @see CallableStatementCreatorFactory
50  * @see SqlParameter
51  * @see SqlTypeValue
52  * @see org.springframework.jdbc.core.support.SqlLobValue
53  */

54 public abstract class StatementCreatorUtils {
55
56     private static final Log logger = LogFactory.getLog(StatementCreatorUtils.class);
57
58     // Determine whether JDK 1.4's CharSequence interface is available,
59
// treating any of its implementations as String value.
60
private static final boolean charSequenceAvailable =
61             ClassUtils.isPresent("java.lang.CharSequence", StatementCreatorUtils.class.getClassLoader());
62
63
64     /**
65      * Set the value for a parameter. The method used is based on the SQL type
66      * of the parameter and we can handle complex types like arrays and LOBs.
67      * @param ps the prepared statement or callable statement
68      * @param paramIndex index of the parameter we are setting
69      * @param declaredParam the parameter as it is declared including type
70      * @param inValue the value to set
71      * @throws SQLException if thrown by PreparedStatement methods
72      */

73     public static void setParameterValue(
74         PreparedStatement JavaDoc ps, int paramIndex, SqlParameter declaredParam, Object JavaDoc inValue)
75         throws SQLException JavaDoc {
76
77         setParameterValue(ps, paramIndex, declaredParam.getSqlType(), declaredParam.getTypeName(), inValue);
78     }
79
80     /**
81      * Set the value for a parameter. The method used is based on the SQL type
82      * of the parameter and we can handle complex types like arrays and LOBs.
83      * @param ps the prepared statement or callable statement
84      * @param paramIndex index of the parameter we are setting
85      * @param sqlType the SQL type of the parameter
86      * @param typeName the type name of the parameter
87      * (optional, only used for SQL NULL and SqlTypeValue)
88      * @param inValue the value to set (plain value or a SqlTypeValue)
89      * @throws SQLException if thrown by PreparedStatement methods
90      * @see SqlTypeValue
91      */

92     public static void setParameterValue(
93         PreparedStatement JavaDoc ps, int paramIndex, int sqlType, String JavaDoc typeName, Object JavaDoc inValue)
94         throws SQLException JavaDoc {
95
96         if (logger.isDebugEnabled()) {
97             logger.debug("Setting SQL statement parameter value: column index " + paramIndex +
98                     ", parameter value [" + inValue +
99                     "], value class [" + (inValue != null ? inValue.getClass().getName() : "null") +
100                     "], SQL type " + (sqlType == SqlTypeValue.TYPE_UNKNOWN ? "unknown" : Integer.toString(sqlType)));
101         }
102
103         if (inValue == null) {
104             if (sqlType == SqlTypeValue.TYPE_UNKNOWN) {
105                 boolean useSetObject = false;
106                 try {
107                     useSetObject = (ps.getConnection().getMetaData().getDatabaseProductName().indexOf("Informix") != -1);
108                 }
109                 catch (Throwable JavaDoc ex) {
110                     logger.debug("Could not check database product name", ex);
111                 }
112                 if (useSetObject) {
113                     ps.setObject(paramIndex, null);
114                 }
115                 else {
116                     ps.setNull(paramIndex, Types.NULL);
117                 }
118             }
119             else if (typeName != null) {
120                 ps.setNull(paramIndex, sqlType, typeName);
121             }
122             else {
123                 ps.setNull(paramIndex, sqlType);
124             }
125         }
126
127         else { // inValue != null
128
if (inValue instanceof SqlTypeValue) {
129                 ((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName);
130             }
131             else if (sqlType == Types.VARCHAR) {
132                 ps.setString(paramIndex, inValue.toString());
133             }
134             else if (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) {
135                 if (inValue instanceof BigDecimal JavaDoc) {
136                     ps.setBigDecimal(paramIndex, (BigDecimal JavaDoc) inValue);
137                 }
138                 else {
139                     ps.setObject(paramIndex, inValue, sqlType);
140                 }
141             }
142             else if (sqlType == Types.DATE) {
143                 if (inValue instanceof java.util.Date JavaDoc) {
144                     if (inValue instanceof java.sql.Date JavaDoc) {
145                         ps.setDate(paramIndex, (java.sql.Date JavaDoc) inValue);
146                     }
147                     else {
148                         ps.setDate(paramIndex, new java.sql.Date JavaDoc(((java.util.Date JavaDoc) inValue).getTime()));
149                     }
150                 }
151                 else if (inValue instanceof Calendar JavaDoc) {
152                     Calendar JavaDoc cal = (Calendar JavaDoc) inValue;
153                     ps.setDate(paramIndex, new java.sql.Date JavaDoc(cal.getTime().getTime()), cal);
154                 }
155                 else {
156                     ps.setObject(paramIndex, inValue, Types.DATE);
157                 }
158             }
159             else if (sqlType == Types.TIME) {
160                 if (inValue instanceof java.util.Date JavaDoc) {
161                     if (inValue instanceof java.sql.Time JavaDoc) {
162                         ps.setTime(paramIndex, (java.sql.Time JavaDoc) inValue);
163                     }
164                     else {
165                         ps.setTime(paramIndex, new java.sql.Time JavaDoc(((java.util.Date JavaDoc) inValue).getTime()));
166                     }
167                 }
168                 else if (inValue instanceof Calendar JavaDoc) {
169                     Calendar JavaDoc cal = (Calendar JavaDoc) inValue;
170                     ps.setTime(paramIndex, new java.sql.Time JavaDoc(cal.getTime().getTime()), cal);
171                 }
172                 else {
173                     ps.setObject(paramIndex, inValue, Types.TIME);
174                 }
175             }
176             else if (sqlType == Types.TIMESTAMP) {
177                 if (inValue instanceof java.util.Date JavaDoc) {
178                     if (inValue instanceof java.sql.Timestamp JavaDoc) {
179                         ps.setTimestamp(paramIndex, (java.sql.Timestamp JavaDoc) inValue);
180                     }
181                     else {
182                         ps.setTimestamp(paramIndex, new java.sql.Timestamp JavaDoc(((java.util.Date JavaDoc) inValue).getTime()));
183                     }
184                 }
185                 else if (inValue instanceof Calendar JavaDoc) {
186                     Calendar JavaDoc cal = (Calendar JavaDoc) inValue;
187                     ps.setTimestamp(paramIndex, new java.sql.Timestamp JavaDoc(cal.getTime().getTime()), cal);
188                 }
189                 else {
190                     ps.setObject(paramIndex, inValue, Types.TIMESTAMP);
191                 }
192             }
193             else if (sqlType == SqlTypeValue.TYPE_UNKNOWN) {
194                 if (isStringValue(inValue)) {
195                     ps.setString(paramIndex, inValue.toString());
196                 }
197                 else if (isDateValue(inValue)) {
198                     ps.setTimestamp(paramIndex, new java.sql.Timestamp JavaDoc(((java.util.Date JavaDoc) inValue).getTime()));
199                 }
200                 else if (inValue instanceof Calendar JavaDoc) {
201                     Calendar JavaDoc cal = (Calendar JavaDoc) inValue;
202                     ps.setTimestamp(paramIndex, new java.sql.Timestamp JavaDoc(cal.getTime().getTime()));
203                 }
204                 else {
205                     // Fall back to generic setObject call without SQL type specified.
206
ps.setObject(paramIndex, inValue);
207                 }
208             }
209             else {
210                 // Fall back to generic setObject call with SQL type specified.
211
ps.setObject(paramIndex, inValue, sqlType);
212             }
213         }
214     }
215
216     /**
217      * Check whether the given value can be treated as a String value.
218      */

219     private static boolean isStringValue(Object JavaDoc inValue) {
220         if (charSequenceAvailable) {
221             // Consider any CharSequence (including JDK 1.5's StringBuilder) as String.
222
return (inValue instanceof CharSequence JavaDoc || inValue instanceof StringWriter JavaDoc);
223         }
224         else {
225             // Explicit enumeration of well-known types for JDK 1.3.
226
return (inValue instanceof String JavaDoc || inValue instanceof StringBuffer JavaDoc || inValue instanceof StringWriter JavaDoc);
227         }
228     }
229
230     /**
231      * Check whether the given value is a <code>java.util.Date</code>
232      * (but not one of the JDBC-specific subclasses).
233      */

234     private static boolean isDateValue(Object JavaDoc inValue) {
235         return (inValue instanceof java.util.Date JavaDoc && !(inValue instanceof java.sql.Date JavaDoc ||
236                 inValue instanceof java.sql.Time JavaDoc || inValue instanceof java.sql.Timestamp JavaDoc));
237     }
238
239     /**
240      * Clean up all resources held by parameter values which were passed to an
241      * execute method. This is for example important for closing LOB values.
242      * @param paramValues parameter values supplied. May be <code>null</code>.
243      * @see DisposableSqlTypeValue#cleanup()
244      * @see org.springframework.jdbc.core.support.SqlLobValue#cleanup()
245      */

246     public static void cleanupParameters(Object JavaDoc[] paramValues) {
247         if (paramValues != null) {
248             cleanupParameters(Arrays.asList(paramValues));
249         }
250     }
251
252     /**
253      * Clean up all resources held by parameter values which were passed to an
254      * execute method. This is for example important for closing LOB values.
255      * @param paramValues parameter values supplied. May be <code>null</code>.
256      * @see DisposableSqlTypeValue#cleanup()
257      * @see org.springframework.jdbc.core.support.SqlLobValue#cleanup()
258      */

259     public static void cleanupParameters(Collection JavaDoc paramValues) {
260         if (paramValues != null) {
261             for (Iterator JavaDoc it = paramValues.iterator(); it.hasNext();) {
262                 Object JavaDoc inValue = it.next();
263                 if (inValue instanceof DisposableSqlTypeValue) {
264                     ((DisposableSqlTypeValue) inValue).cleanup();
265                 }
266             }
267         }
268     }
269
270 }
271
Popular Tags