KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > jdo > spi > persistence > support > sqlstore > sql > generator > DBStatement


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * DBStatement.java
26  *
27  * Created on March 3, 2000
28  *
29  */

30
31 package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator;
32
33 import org.netbeans.modules.dbschema.ColumnElement;
34 import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore;
35 import com.sun.jdo.spi.persistence.support.sqlstore.database.DBVendorType;
36 import com.sun.jdo.spi.persistence.support.sqlstore.model.LocalFieldDesc;
37 import com.sun.jdo.spi.persistence.utility.logging.Logger;
38
39 import java.io.ByteArrayInputStream JavaDoc;
40 import java.io.StringReader JavaDoc;
41 import java.math.BigDecimal JavaDoc;
42 import java.math.BigInteger JavaDoc;
43 import java.sql.*;
44
45 /**
46  */

47 public class DBStatement extends Object JavaDoc {
48
49     /** Name of the batch threshold property. */
50     public static final String JavaDoc BATCH_THRESHOLD_PROPERTY =
51         "com.sun.jdo.spi.persistence.support.sqlstore.BATCH_THRESHOLD";
52
53     /**
54      * Batch threshold. Set the value from the system property named by
55      * this class followed by "BATCH_THRESHOLD". Default is 100.
56      */

57     private static final int BATCH_THRESHOLD =
58         Integer.getInteger(BATCH_THRESHOLD_PROPERTY, 100).intValue();
59
60     /** The wrapped PreparedStatement. */
61     private PreparedStatement preparedStmt;
62
63     /** Current number of batched commands. */
64     private int batchCounter = 0;
65
66     /** The SQL text. */
67     private String JavaDoc statementText;
68
69     /** The logger */
70     private static Logger logger = LogHelperSQLStore.getLogger();
71
72     /**
73      * This constructor is used for batched updates.
74      * @param conn the connection
75      * @param statementText the statement text
76      * @param timeout the query timeout
77      */

78     public DBStatement(Connection conn, String JavaDoc statementText, int timeout)
79         throws SQLException
80     {
81         this.statementText = statementText;
82         preparedStmt = conn.prepareStatement(statementText);
83         // Set SELECT/INSERT/UPDATE/DELETE Statement timeout
84
preparedStmt.setQueryTimeout(timeout);
85     }
86
87     /** Returns the SQL text. */
88     public String JavaDoc getStatementText()
89     {
90         return statementText;
91     }
92
93     /** Returns the wrapped PreparedStatement. */
94     public PreparedStatement getPreparedStatement()
95     {
96         return preparedStmt;
97     }
98
99     /**
100      * Checks whether the current number of batched commands exceeds the
101      * batch threshold defined by {@link #BATCH_THRESHOLD}.
102      */

103     public boolean exceedsBatchThreshold()
104     {
105         return batchCounter >= BATCH_THRESHOLD;
106     }
107
108     /**
109      * Increases the batch counter and delegates the addBatch call to the
110      * PreparedStatement wrapped by this DBStatement.
111      */

112     public void addBatch()
113         throws SQLException
114     {
115         batchCounter++;
116         if (logger.isLoggable(Logger.FINER)) {
117             logger.finer("sqlstore.sql.generator.dbstatement.addbatch", // NOI18N
118
new Integer JavaDoc(batchCounter));
119         }
120         preparedStmt.addBatch();
121     }
122
123     /**
124      * Delegates the executeBatch call to the PreparedStatement wrapped by
125      * this DBStatement and resets the batch counter.
126      */

127     public int[] executeBatch()
128         throws SQLException
129     {
130         if (logger.isLoggable(Logger.FINER)) {
131             logger.finer("sqlstore.sql.generator.dbstatement.executebatch", // NOI18N
132
new Integer JavaDoc(batchCounter));
133         }
134         batchCounter = 0;
135         return preparedStmt.executeBatch();
136     }
137
138     /**
139      * Delegates the executeUpdate call to the PreparedStatement wrapped by
140      * this DBStatement.
141      */

142     public int executeUpdate()
143         throws SQLException
144     {
145         return preparedStmt.executeUpdate();
146     }
147
148     /**
149      * Delegates the executeQuery call to the PreparedStatement wrapped by
150      * this DBStatement.
151      */

152     public ResultSet executeQuery()
153         throws SQLException
154     {
155         return preparedStmt.executeQuery();
156     }
157
158     /**
159      * Delegates the close call to the PreparedStatement wrapped by
160      * this DBStatement.
161      */

162     public void close()
163         throws SQLException
164     {
165         if (preparedStmt != null) {
166             preparedStmt.close();
167     }
168     }
169
170     /**
171      * Binds the specified value to the column corresponding with
172      * the specified index reference.
173      * @param index the index
174      * @param val the value
175      * @param columnElement the columnElement corresponding to the parameter
176      * marker at specified index. This parameter will always contain correct
177      * value when called for sql statements corresponding to insert and update
178      * For select statements this parameter can be null if query compiler is not
179      * able to detect java field for a parameter or value passed to the query.
180      * Please see RetrieveDescImpl#addValueConstraint for more information
181      *
182      * @param vendorType the vendor type
183      * @throws SQLException thrown by setter methods on java.sql.PreparedStatement
184      * @see com.sun.jdo.spi.persistence.support.sqlstore.sql.RetrieveDescImpl#addValueConstraint
185      */

186     public void bindInputColumn(int index, Object JavaDoc val, ColumnElement columnElement, DBVendorType vendorType)
187         throws SQLException
188     {
189         int sqlType = getSqlType(columnElement);
190         if (logger.isLoggable(Logger.FINER)) {
191             Object JavaDoc[] items = {new Integer JavaDoc(index),val,new Integer JavaDoc(sqlType)};
192             logger.finer("sqlstore.sql.generator.dbstatement.bindinputcolumn", items); // NOI18N
193
}
194
195         if (val == null) {
196             //setNull is called only for insert and update statement to set a column
197
//to null value. We will always have valid sqlType in this case
198
preparedStmt.setNull(index, sqlType);
199         } else {
200             if (val instanceof Number JavaDoc) {
201                 Number JavaDoc number = (Number JavaDoc) val;
202                 if (number instanceof Integer JavaDoc) {
203                     preparedStmt.setInt(index, number.intValue());
204                 } else if (number instanceof Long JavaDoc) {
205                     preparedStmt.setLong(index, number.longValue());
206                 } else if (number instanceof Short JavaDoc) {
207                     preparedStmt.setShort(index, number.shortValue());
208                 } else if (number instanceof Byte JavaDoc) {
209                     preparedStmt.setByte(index, number.byteValue());
210                 } else if (number instanceof Double JavaDoc) {
211                     preparedStmt.setDouble(index, number.doubleValue());
212                 } else if (number instanceof Float JavaDoc) {
213                     preparedStmt.setFloat(index, number.floatValue());
214                 } else if (number instanceof BigDecimal JavaDoc) {
215                     preparedStmt.setBigDecimal(index, (BigDecimal JavaDoc) number);
216                 } else if (number instanceof BigInteger JavaDoc) {
217                     preparedStmt.setBigDecimal(index, new BigDecimal JavaDoc((BigInteger JavaDoc) number));
218                 }
219             } else if (val instanceof String JavaDoc) {
220                 bindStringValue(index, (String JavaDoc)val, columnElement, vendorType);
221             } else if (val instanceof Boolean JavaDoc) {
222                 preparedStmt.setBoolean(index, ((Boolean JavaDoc) val).booleanValue());
223             } else if (val instanceof java.util.Date JavaDoc) {
224                 if (val instanceof java.sql.Date JavaDoc) {
225                     preparedStmt.setDate(index, (java.sql.Date JavaDoc) val);
226                 } else if (val instanceof Time) {
227                     preparedStmt.setTime(index, (Time) val);
228                 } else if (val instanceof Timestamp) {
229                     preparedStmt.setTimestamp(index, (Timestamp) val);
230                 } else {
231                     Timestamp timestamp = new Timestamp(((java.util.Date JavaDoc) val).getTime());
232                     preparedStmt.setTimestamp(index, timestamp);
233                 }
234             } else if (val instanceof Character JavaDoc) {
235                 bindStringValue(index, val.toString(), columnElement, vendorType);
236             } else if (val instanceof byte[]) {
237                 //
238
// We use setBinaryStream() because of a limit on the maximum
239
// array size that can be bound using the
240
// PreparedStatement class setBytes() method on Oracle.
241
//
242
//preparedStmt.setBytes(index, (byte[]) val);
243
byte[] ba = (byte[]) val;
244                 preparedStmt.setBinaryStream(index, new ByteArrayInputStream JavaDoc(ba), ba.length);
245             } else if (val instanceof Blob) {
246                 preparedStmt.setBlob(index, (Blob) val);
247             } else if (val instanceof Clob) {
248                 preparedStmt.setClob(index, (Clob) val);
249             } else {
250                 preparedStmt.setObject(index, val);
251             }
252         }
253     }
254     
255     /**
256      * Binds the specified value to the column corresponding with
257      * the specified index reference.
258      * @param index the index
259      * @param strVal the value
260      * @param columnElement Descripion of the database column.
261      * @param vendorType the vendor type
262      * @throws SQLException thrown by setter methods on java.sql.PreparedStatement
263      */

264     private void bindStringValue(int index, String JavaDoc strVal, ColumnElement columnElement, DBVendorType vendorType)
265         throws SQLException {
266
267         int sqlType = getSqlType(columnElement);
268         if(LocalFieldDesc.isCharLobType(sqlType) ) {
269             //Correct sqlType is passed for parameter markers which do not belong to where clause
270
//So for insert and update statement we can safely detect binding to character LOB here.
271
//
272
//For parameter markers belonging to where clause, we do not always receive correct sqlType.
273
//It is not allowed by any db to have a Character LOB type in where clause except
274
//for null comparison. Let the db report an error if user puts a field mapped
275
//to character LOB column in where clause.
276
preparedStmt.setCharacterStream(index, new StringReader JavaDoc(strVal), strVal.length());
277         } else if(LocalFieldDesc.isFixedCharType(sqlType) ) {
278             vendorType.getSpecialDBOperation().bindFixedCharColumn(preparedStmt, index,
279                     strVal, getLength(columnElement) );
280         } else {
281             preparedStmt.setString(index, strVal);
282         }
283     }
284
285     private static int getSqlType(ColumnElement columnElement) {
286         return (columnElement != null) ? columnElement.getType() : Types.OTHER;
287     }
288
289     private static int getLength(ColumnElement columnElement) {
290         int length = -1;
291         if(columnElement != null) {
292             Integer JavaDoc l = columnElement.getLength();
293             if(l != null) {
294                 length = l.intValue();
295             }
296         }
297         return length;
298     }
299 }
300
Popular Tags