仿valuelist式动态sql拼装

   非常喜欢valuelist拼sql的处理方式,遂写了该工具类,这下也可以弥补hibernate动态sql的缺陷了,将来应该会用到
<?xml version="1.0" encoding="UTF-8" ?>
<sql-definition>
	<sqls>
		<sql name="sql1">
			select 1 from dual
			where 1=1
			/~name: and name={name}~/
			/~age: and age={age}~/
			order by 1
		</sql>
		<sql name="sql2">
			select 1 from dualx
			where 1=1
			/~name: and name={name}~/
			/~age: and age={age}~/
			order by 1
		</sql>
	</sqls>
</sql-definition>


public class SqlUtil {
	
	private static String startToken = "/~";
	private static String endToken = "~/";
	private static String XML_FILE_PATH="sql.xml";
	private static Map<String, StringBuilder> sqls=new HashMap<String, StringBuilder>();
	
	static {
		init();
	}
	
	public static StringBuilder getSql(String sqlName,Map<String, Object> queryMap){
		return  manipulate(sqls.get(sqlName), queryMap);
	}
	
	private static StringBuilder manipulate(StringBuilder text ,Map<String , Object> model){
		for (int start = 0, end = text.indexOf(endToken); ((end = text.indexOf(endToken)) >= 0);){
			start = text.lastIndexOf(startToken, end);
	        String key = text.substring(start + 2, text.indexOf(":", start));
	        Object modelValue = model.get(key);
	        if(modelValue==null){
	        	text.replace(start, end + 2, "");
	        }else{
	        	text.replace(start, end + 2, text.substring(text.indexOf(":", start) + 1, end));
	        }
	        
		}
		String valueStartToken="{";
		String valueEndToken="}";
		for (int start = 0, end = text.indexOf(valueEndToken); ((end = text.indexOf(valueEndToken)) >= 0);){
			start=text.lastIndexOf(valueStartToken,end);
			String key = text.substring(start + valueStartToken.length(), end);
			Object modelValue = model.get(key);
	        if(modelValue==null){
	        	text.replace(start, end + valueEndToken.length(), "");
	        }else{
	        	String value;
	        	if(modelValue instanceof String){
	        		
	        		value="'"+modelValue+"'";
	        	}else{
	        		value=modelValue+"";
	        	}
	        	text.replace(start, end + valueEndToken.length(), value);
	        }
		}
		return text;
	}
	
	@SuppressWarnings("unchecked")
	private static void init(){
		try {
			Configuration config = new XMLConfiguration(XML_FILE_PATH);
			List<String> sqllist =config.getList("sqls.sql");
			for (int i = 0; i < sqllist.size(); i++) {
				String sql = config.getString("sqls.sql("+i+")");
				String name = config.getString("sqls.sql("+i+")[@name]");
				sqls.put(name, new StringBuilder(sql));
			}
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}
	@Deprecated
	public static void reInit(){
		sqls.clear();
		init();
	}
	
	
	public static void main(String[] args) {
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("name", null);
		map.put("age", 45);
		StringBuilder sql = SqlUtil.getSql("sql1", map);
		System.out.println(sql);
	}

}

你可能感兴趣的:(sql,Hibernate,xml)