1 package org.hibernate.sql; 3 4 import org.hibernate.dialect.Dialect; 5 import org.hibernate.HibernateException; 6 7 import java.util.List ; 8 import java.util.ArrayList ; 9 import java.util.Iterator ; 10 11 16 public class InsertSelect { 17 18 private Dialect dialect; 19 private String tableName; 20 private String comment; 21 private List columnNames = new ArrayList (); 22 private Select select; 23 24 public InsertSelect(Dialect dialect) { 25 this.dialect = dialect; 26 } 27 28 public InsertSelect setTableName(String tableName) { 29 this.tableName = tableName; 30 return this; 31 } 32 33 public InsertSelect setComment(String comment) { 34 this.comment = comment; 35 return this; 36 } 37 38 public InsertSelect addColumn(String columnName) { 39 columnNames.add( columnName ); 40 return this; 41 } 42 43 public InsertSelect addColumns(String [] columnNames) { 44 for ( int i = 0; i < columnNames.length; i++ ) { 45 this.columnNames.add( columnNames[i] ); 46 } 47 return this; 48 } 49 50 public InsertSelect setSelect(Select select) { 51 this.select = select; 52 return this; 53 } 54 55 public String toStatementString() { 56 if ( tableName == null ) throw new HibernateException( "no table name defined for insert-select" ); 57 if ( select == null ) throw new HibernateException( "no select defined for insert-select" ); 58 59 StringBuffer buf = new StringBuffer ( (columnNames.size() * 15) + tableName.length() + 10 ); 60 if ( comment!=null ) { 61 buf.append( "/* " ).append( comment ).append( " */ " ); 62 } 63 buf.append( "insert into " ).append( tableName ); 64 if ( !columnNames.isEmpty() ) { 65 buf.append( " (" ); 66 Iterator itr = columnNames.iterator(); 67 while ( itr.hasNext() ) { 68 buf.append( itr.next() ); 69 if ( itr.hasNext() ) { 70 buf.append( ", " ); 71 } 72 } 73 buf.append( ")" ); 74 } 75 buf.append( ' ' ).append( select.toStatementString() ); 76 return buf.toString(); 77 } 78 } 79 | Popular Tags |