您的位置:首页 > 数据库

bean 反射生成插入的sql

2015-09-15 21:11 344 查看
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanUtil {

static Map<String,Method> getTypeMethod(Class clazz,String type){

Method[] methods = clazz.getMethods();
Map<String,Method> map = new HashMap<String, Method>();

for(Method method:methods){
String sb = method.getName().toLowerCase();
int pos = sb.toLowerCase().indexOf(type);
if(pos > -1){
map.put(sb.substring(type.length()), method);
}
}
return map;
}
/*获取get方法名称
* */
static Map<String,Method> getGetMethod(Class clazz){
return getTypeMethod(clazz,"get");
}
/*
* 获取set方法名称
*/
static Map<String,Method> getSetMethod(Class clazz){
return getTypeMethod(clazz,"set");
}
public static StringBuilder genreateSql(List<?> beanList,String tablename){
if(null != beanList && beanList.size() > 0){
Class clazz = beanList.get(0).getClass();
StringBuilder sql = new StringBuilder("");
Map<String,Method> getmethods = getGetMethod(clazz);
Map<String,Method> setmethods = getSetMethod(clazz);
sql.append("insert into ").append(tablename).append(" (");
List<Property> props = new ArrayList<Property>();
for(Map.Entry<String, Method> entry:getmethods.entrySet()){
String key = entry.getKey();
Method getmethod = entry.getValue();
if(null != setmethods.get(key)){

Class rtncls= getmethod.getReturnType();
Property prop = new Property();
if(rtncls == int.class || rtncls == Integer.class ||rtncls == float.class || rtncls == Float.class ||
rtncls == double.class || rtncls == Double.class){
prop.setType(1);

}else if(rtncls == String.class || rtncls == Date.class){
prop.setType(0);
}
else{
continue;
}
prop.setName(key);
props.add(prop);
sql.append(key).append(",");
}
}
sql.deleteCharAt(sql.length()-1).append(") values ");
for(Object bean : beanList){
sql.append("(");
for(Property prop : props){
Method getMehod = getmethods.get(prop.getName());
try {
prop.append(sql, getMehod.invoke(bean));
sql.append(",");
} catch (Exception e) {
e.printStackTrace();
}
}
sql.deleteCharAt(sql.length()-1);
sql.append(") ,");
}
sql.deleteCharAt(sql.length()-1);

//System.out.println(sql);
return sql;
}

return null;
}

}
class Property{
private String name;
private int  type;/*判断类型,时候添加*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public StringBuilder append(StringBuilder sb,Object val){

if(val == null) return sb.append("null");
if(1 == type){
return sb.append(val);
}
return sb.append("'").append(val).append("'");
}
}

指定表的名称,然后需要bean的对象的属性名称与表中的字段名称一致,这样就可以生成要插入的sql了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: