01: // $Id: InsertSelect.java 7057 2005-06-07 20:06:10Z steveebersole $
02: package org.hibernate.sql;
03:
04: import org.hibernate.dialect.Dialect;
05: import org.hibernate.HibernateException;
06:
07: import java.util.List;
08: import java.util.ArrayList;
09: import java.util.Iterator;
10:
11: /**
12: * Implementation of InsertSelect.
13: *
14: * @author Steve Ebersole
15: */
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)
57: throw new HibernateException(
58: "no table name defined for insert-select");
59: if (select == null)
60: throw new HibernateException(
61: "no select defined for insert-select");
62:
63: StringBuffer buf = new StringBuffer((columnNames.size() * 15)
64: + tableName.length() + 10);
65: if (comment != null) {
66: buf.append("/* ").append(comment).append(" */ ");
67: }
68: buf.append("insert into ").append(tableName);
69: if (!columnNames.isEmpty()) {
70: buf.append(" (");
71: Iterator itr = columnNames.iterator();
72: while (itr.hasNext()) {
73: buf.append(itr.next());
74: if (itr.hasNext()) {
75: buf.append(", ");
76: }
77: }
78: buf.append(")");
79: }
80: buf.append(' ').append(select.toStatementString());
81: return buf.toString();
82: }
83: }
|