1 package org.hibernate.sql; 3 4 import java.util.Iterator ; 5 import java.util.Map ; 6 7 import org.apache.commons.collections.SequencedHashMap; 8 import org.hibernate.dialect.Dialect; 9 import org.hibernate.type.LiteralType; 10 11 16 public class Insert { 17 18 public Insert(Dialect dialect) { 19 this.dialect = dialect; 20 } 21 22 private String comment; 23 public Insert setComment(String comment) { 24 this.comment = comment; 25 return this; 26 } 27 28 private Dialect dialect; 29 private String tableName; 30 31 private Map columns = new SequencedHashMap(); 32 33 public Insert addColumn(String columnName) { 34 return addColumn(columnName, "?"); 35 } 36 37 public Insert addColumns(String [] columnNames) { 38 for ( int i=0; i<columnNames.length; i++ ) { 39 addColumn( columnNames[i] ); 40 } 41 return this; 42 } 43 44 public Insert addColumns(String [] columnNames, boolean[] insertable) { 45 for ( int i=0; i<columnNames.length; i++ ) { 46 if ( insertable[i] ) addColumn( columnNames[i] ); 47 } 48 return this; 49 } 50 51 public Insert addColumn(String columnName, String value) { 52 columns.put(columnName, value); 53 return this; 54 } 55 56 public Insert addColumn(String columnName, Object value, LiteralType type) throws Exception { 57 return addColumn( columnName, type.objectToSQLString(value) ); 58 } 59 60 public Insert addIdentityColumn(String columnName) { 61 String value = dialect.getIdentityInsertString(); 62 if (value!=null) addColumn(columnName, value); 63 return this; 64 } 65 66 public Insert setTableName(String tableName) { 67 this.tableName = tableName; 68 return this; 69 } 70 71 public String toStatementString() { 72 StringBuffer buf = new StringBuffer ( columns.size()*15 + tableName.length() + 10 ); 73 if (comment!=null) buf.append("/* ").append(comment).append(" */ "); 74 buf.append("insert into ") 75 .append(tableName); 76 if ( columns.size()==0 ) { 77 buf.append(' ').append( dialect.getNoColumnsInsertString() ); 78 } 79 else { 80 buf.append(" ("); 81 Iterator iter = columns.keySet().iterator(); 82 while ( iter.hasNext() ) { 83 buf.append( iter.next() ); 84 if ( iter.hasNext() ) buf.append(", "); 85 } 86 buf.append(") values ("); 87 iter = columns.values().iterator(); 88 while ( iter.hasNext() ) { 89 buf.append( iter.next() ); 90 if ( iter.hasNext() ) buf.append(", "); 91 } 92 buf.append(')'); 93 } 94 return buf.toString(); 95 } 96 } 97 | Popular Tags |