实现一个简单处理sql语句的类
程序员文章站
2022-06-05 09:25:36
...
import java.util.Enumeration;
import java.util.Hashtable;
import org.junit.Test;
import com.crz.utils.log.LogUtil;
/**
*
* @Title: StringToHql.java
* @Description: TODO(字符串转换为hql语句)
* @author [email protected]
* @date 2010-4-30
* @version V1.3
*/
public class StringToHql {
private String hql ="";
private Hashtable map = null;
//初始化1
public StringToHql(){
}
//初始化2
public StringToHql(String hql){
map = new Hashtable(); //初始化
this.hql = hql;
}
/**
* 创建hql语句
*/
public StringToHql createQuery(String hql){
map = new Hashtable(); //初始化
this.hql = hql;
return this;
}
/**设置String类型参数*/
public StringToHql setParameterString(String name,String val){
map.put(name, val);
return this;
}
/**设置Integer类型参数*/
public StringToHql setParameterString(String name,Integer val){
map.put(name, val);
return this;
}
/**设置Double类型参数*/
public StringToHql setParameterString(String name,Double val){
map.put(name,val);
return this;
}
/**
* 处理hql语句(数据库标准的hql)
*/
public String doHql(){
if(hql!=null && !"".equals(hql)){
String tem = "";
Enumeration e = map.keys();
while(e.hasMoreElements()){
tem = (String)e.nextElement(); //key ~ String
if(map.get(tem) instanceof Integer) {
this.hql = hql.replace(":" + tem, "" +(Integer) map.get(tem)+" ");
}else if(map.get(tem) instanceof String){
this.hql = hql.replace(":" + tem, "'" +(String) map.get(tem)+"'");
}else if(map.get(tem) instanceof Double){
this.hql = hql.replace(":" + tem, "" +(Double) map.get(tem)+" ");
}
}
}else {
System.out.println("没有sql语句");
}
LogUtil.info("这次调用的sql语名[StringToHql]: " + hql);
return hql;
}
/**
* 测试,使用方法
*/
@Test
public void test1(){
StringToHql st = new StringToHql();
st.createQuery("from Manager where anutoh=:anutoh");
st.setParameterString("anutoh", "小明");
String hql = st.doHql();
System.out.println(hql);
}
@Test
public void test2(){
String hql = new StringToHql("from Manager where anutoh=:anutoh and mone=:mone")
.setParameterString("anutoh", "小明2")
.setParameterString("mone", 4500.5)
.doHql();
System.out.println(hql);
}
}