1 package org.hibernate.sql; 3 4 import java.util.ArrayList ; 5 import java.util.Iterator ; 6 import java.util.List ; 7 8 import org.hibernate.util.StringHelper; 9 10 17 public class InFragment { 18 19 public static final String NULL = "null"; 20 public static final String NOT_NULL = "not null"; 21 22 private String columnName; 23 private List values = new ArrayList (); 24 25 28 public InFragment addValue(Object value) { 29 values.add(value); 30 return this; 31 } 32 33 public InFragment setColumn(String columnName) { 34 this.columnName = columnName; 35 return this; 36 } 37 38 public InFragment setColumn(String alias, String columnName) { 39 this.columnName = StringHelper.qualify(alias, columnName); 40 return setColumn(this.columnName); 41 } 42 43 public InFragment setFormula(String alias, String formulaTemplate) { 44 this.columnName = StringHelper.replace(formulaTemplate, Template.TEMPLATE, alias); 45 return setColumn(this.columnName); 46 } 47 48 public String toFragmentString() { 49 if ( values.size()==0 ) return "1=2"; 50 StringBuffer buf = new StringBuffer ( values.size() * 5 ); 51 buf.append(columnName); 52 if ( values.size()>1 ) { 55 boolean allowNull = false; 56 buf.append(" in ("); 57 Iterator iter = values.iterator(); 58 while ( iter.hasNext() ) { 59 Object value = iter.next(); 60 if ( NULL.equals(value) ) { 61 allowNull = true; 62 } 63 else if ( NOT_NULL.equals(value) ) { 64 throw new IllegalArgumentException ("not null makes no sense for in expression"); 65 } 66 else { 67 buf.append(value); 68 buf.append(", "); 69 } 70 } 71 buf.setLength( buf.length()-2 ); 72 buf.append(')'); 73 if (allowNull) { 74 buf.insert(0, " is null or ") 75 .insert(0, columnName) 76 .insert(0, '(') 77 .append(')'); 78 } 79 } 80 else { 81 Object value = values.iterator().next(); 82 if ( NULL.equals(value) ) { 83 buf.append(" is null"); 84 } 85 else if ( NOT_NULL.equals(value) ) { 86 buf.append(" is not null"); 87 } 88 else { 89 buf.append("=").append(value); 90 } 91 } 92 return buf.toString(); 93 } 94 } 95 | Popular Tags |