实现一个简单处理sql语句的类

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 awfhome@163.com 
 * @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);
		
	}
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值