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.1 2007-08-24 22:17:39 ewestfal Exp $
030 */
031 public class SqlInsertStatement extends SqlPkStatement
032 {
033 private String sql;
034
035 /**
036 * Constructor for SqlInsertStatement.
037 *
038 * @param cld
039 * @param logger
040 */
041 public SqlInsertStatement(ClassDescriptor cld, Logger logger)
042 {
043 super(cld, logger);
044 }
045
046 /** @see SqlStatement#getStatement() */
047 public String getStatement()
048 {
049 if(sql == null)
050 {
051 StringBuffer stmt = new StringBuffer(1024);
052 ClassDescriptor cld = getClassDescriptor();
053
054 stmt.append("INSERT INTO ");
055 appendTable(cld, stmt);
056 stmt.append(" (");
057 appendListOfColumns(cld, stmt);
058 stmt.append(")");
059 appendListOfValues(cld, stmt);
060
061 sql = stmt.toString();
062 }
063 return sql;
064 }
065
066 private List appendListOfColumns(ClassDescriptor cld, StringBuffer buf)
067 {
068 FieldDescriptor[] fields = cld.getAllRwFields();
069
070 ArrayList columnList = new ArrayList();
071
072 for(int i = 0; i < fields.length; i++)
073 {
074 if(i > 0)
075 {
076 buf.append(",");
077 }
078 buf.append(fields[i].getColumnName());
079 columnList.add(fields[i].getAttributeName());
080 }
081 return columnList;
082 }
083
084 /**
085 * generates a values(?,) for a prepared insert statement.
086 * returns null if there are no fields
087 * @param stmt the StringBuffer
088 */
089 private void appendListOfValues(ClassDescriptor cld, StringBuffer stmt)
090 {
091 FieldDescriptor[] fields = cld.getAllRwFields();
092
093 if(fields.length == 0)
094 {
095 return;
096 }
097
098 stmt.append(" VALUES (");
099 for(int i = 0; i < fields.length; i++)
100 {
101 stmt.append("?");
102 if(i < fields.length - 1)
103 {
104 stmt.append(",");
105 }
106 }
107 stmt.append(") ");
108 }
109
110 }
111