public class Test{
/** *//**
* Test Method
*/
private void service(){
String param[] = {
"name", "id"
};
Object values[] = {
"minli", 1
};
update("Customer", param, values);
}
/** *//**
* 更新 (该方法目前只针对一个查询参数,至于多参数的可以在此基础上更改,思路则不变)
* @params 为要更新实体当中的属性,其中最后一个为查询参数
*/
private void update(String entity, String[] params, Object[] values){
if (params == null || values == null)
throw new NullPointerException("param is null!");
if (params.length < 2 || values.length < 2)
throw new IllegalArgumentException("param is wrong");
if (params.length != values.length)
throw new IllegalArgumentException("param is wrong");
String updateHQL = updateSQL(entity, params, values);
//这个地方可以使用query来进行遍历数组来赋值
System.out.println(updateHQL);
}
/** *//**
* 生成Update HQL语句
*/
private String updateSQL(String entity, String[] params, Object[] values){
String entityName = entity.toLowerCase();
String baseHQL = "update " + entity + " " + entityName + " set ";
for (int i = 0; i < params.length - 1; i++){
String param = params[i];
baseHQL += entityName + "." + param + "=:" + param;
if (i < params.length - 2)
baseHQL += ",";
}
String param = params[params.length - 1];
baseHQL += " where " + entityName + "." + param + "=:" + param;
return baseHQL;
}
public static void main(String[] args){
new Test().service();
}
}