import java.lang.reflect.*;
public class BeanUtil {
//这是拼接查询SQL语句的方法(getDelectSQL)
public static String getDeleteSQL(Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class<? extends Object> classzz=obj.getClass();
String tableName=classzz.getSimpleName();
StringBuffer sbsql=new StringBuffer();
sbsql.append("Select * Form "+tableName+" ");
sbsql.append(" Where 1=1 ");
Field[] fields =classzz.getDeclaredFields();
for(Field f:fields){
String methodName="get"+ f.getName().substring(0,1).toUpperCase()+ f.getName().substring(1);
Method m=classzz.getDeclaredMethod(methodName);
Object o=m.invoke(obj);
if(o!=null){
if(o instanceof String){
sbsql.append(" And "+f.getName()+"='"+o+"'");
}else{
sbsql.append(" And "+f.getName()+"="+o);
}
}
}
return sbsql.toString();
}
//这是拼接更新SQL语句的方法(getUpdate)
public static String getUpdate(Object obj) throws IllegalArgumentException, IllegalAccessException{
Class<? extends Object> classzz=obj.getClass();
String tableName=classzz.getSimpleName();
String sql1="Update "+tableName+" Set ";
String sql2=" ";
String sql3=" Where ";
Field[] fields=classzz.getDeclaredFields();
for(Field f :fields){
f.setAccessible(true);
Object value=f.get(obj);
//下面IF中的代码表示如果该字段满足PrimaryKey这个注解,则返回true,否则为false
if(f.isAnnotationPresent(PrimaryKey.class)){
if(value instanceof String){
sql3 += f.getName()+"='"+value+"'";
}else{
sql3 += f.getName()+"="+value+"";
}
}else{
if(value instanceof String){
sql2 += f.getName()+"='"+value+"',";
}else{
sql2 += f.getName()+"="+value+",";
}
}
}
sql2=sql2.substring(0,sql2.length()-2);
sql1= sql1+sql2+sql3;
return sql1;
}
}