KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > sql > InsertSelect


1 // $Id: InsertSelect.java,v 1.1 2005/06/07 20:06:10 steveebersole Exp $
2
package org.hibernate.sql;
3
4 import org.hibernate.dialect.Dialect;
5 import org.hibernate.HibernateException;
6
7 import java.util.List JavaDoc;
8 import java.util.ArrayList JavaDoc;
9 import java.util.Iterator JavaDoc;
10
11 /**
12  * Implementation of InsertSelect.
13  *
14  * @author Steve Ebersole
15  */

16 public class InsertSelect {
17
18     private Dialect dialect;
19     private String JavaDoc tableName;
20     private String JavaDoc comment;
21     private List JavaDoc columnNames = new ArrayList JavaDoc();
22     private Select select;
23
24     public InsertSelect(Dialect dialect) {
25         this.dialect = dialect;
26     }
27
28     public InsertSelect setTableName(String JavaDoc tableName) {
29         this.tableName = tableName;
30         return this;
31     }
32
33     public InsertSelect setComment(String JavaDoc comment) {
34         this.comment = comment;
35         return this;
36     }
37
38     public InsertSelect addColumn(String JavaDoc columnName) {
39         columnNames.add( columnName );
40         return this;
41     }
42
43     public InsertSelect addColumns(String JavaDoc[] 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 JavaDoc 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 JavaDoc buf = new StringBuffer JavaDoc( (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 JavaDoc 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