001: package org.apache.ojb.broker.accesslayer.sql;
002:
003: /* Copyright 2002-2005 The Apache Software Foundation
004: *
005: * Licensed under the Apache License, Version 2.0 (the "License");
006: * you may not use this file except in compliance with the License.
007: * You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017:
018: import java.util.ArrayList;
019: import java.util.List;
020:
021: import org.apache.ojb.broker.metadata.ClassDescriptor;
022: import org.apache.ojb.broker.metadata.FieldDescriptor;
023: import org.apache.ojb.broker.util.logging.Logger;
024:
025: /**
026: * Model an INSERT Statement
027: *
028: * @author <a href="mailto:jbraeuchi@hotmail.com">Jakob Braeuchi</a>
029: * @version $Id: SqlInsertStatement.java,v 1.7.2.2 2005/12/21 22:23:43 tomdz Exp $
030: */
031: public class SqlInsertStatement extends SqlPkStatement {
032: private String sql;
033:
034: /**
035: * Constructor for SqlInsertStatement.
036: *
037: * @param cld
038: * @param logger
039: */
040: public SqlInsertStatement(ClassDescriptor cld, Logger logger) {
041: super (cld, logger);
042: }
043:
044: /** @see SqlStatement#getStatement() */
045: public String getStatement() {
046: if (sql == null) {
047: StringBuffer stmt = new StringBuffer(1024);
048: ClassDescriptor cld = getClassDescriptor();
049:
050: stmt.append("INSERT INTO ");
051: appendTable(cld, stmt);
052: stmt.append(" (");
053: appendListOfColumns(cld, stmt);
054: stmt.append(")");
055: appendListOfValues(cld, stmt);
056:
057: sql = stmt.toString();
058: }
059: return sql;
060: }
061:
062: private List appendListOfColumns(ClassDescriptor cld,
063: StringBuffer buf) {
064: FieldDescriptor[] fields = cld.getAllRwFields();
065:
066: ArrayList columnList = new ArrayList();
067:
068: for (int i = 0; i < fields.length; i++) {
069: if (i > 0) {
070: buf.append(",");
071: }
072: buf.append(fields[i].getColumnName());
073: columnList.add(fields[i].getAttributeName());
074: }
075: return columnList;
076: }
077:
078: /**
079: * generates a values(?,) for a prepared insert statement.
080: * returns null if there are no fields
081: * @param stmt the StringBuffer
082: */
083: private void appendListOfValues(ClassDescriptor cld,
084: StringBuffer stmt) {
085: FieldDescriptor[] fields = cld.getAllRwFields();
086:
087: if (fields.length == 0) {
088: return;
089: }
090:
091: stmt.append(" VALUES (");
092: for (int i = 0; i < fields.length; i++) {
093: stmt.append("?");
094: if (i < fields.length - 1) {
095: stmt.append(",");
096: }
097: }
098: stmt.append(") ");
099: }
100:
101: }
|