根据反射生成SQL语句
1 /** 2 * 基础查询语句 3 * 返回类型的属性字符串Sql 4 * @author: InkYi 5 * 修改时间:2016年5月11日 - 上午10:06:00<br/> 6 * 功能说明:<br/> 7 * @param clazz 8 * @return "id,name,sex....." 9 */ 10 private String baseSelectSQL(Class clazz){ 11 StringBuffer sb = new StringBuffer(); 12 Field[] fields = clazz.getDeclaredFields(); 13 for (int i = 0; i < fields.length; i++) { 14 Field field = fields[i]; 15 field.setAccessible( true ); 16 sb.append(field.getName()); 17 sb.append(", "); 18 try { 19 Object object = field.get(clazz); 20 System.out.println(object.toString()); 21 } catch (IllegalArgumentException | IllegalAccessException e) { 22 e.printStackTrace(); 23 } 24 } 25 int lastIndexOf = sb.lastIndexOf(", "); 26 sb.delete(lastIndexOf, sb.length()); 27 return sb.toString(); 28 }
1 /** 2 * 基础条件语句 3 * 只返回属性不为空的属性和值 4 * @author: InkYi 5 * 修改时间:2016年5月11日 - 上午10:52:26<br/> 6 * 功能说明:<br/> 7 * @param obj 8 * @return SELECT & DELETE-->id='0' AND name='inkyi' 9 * 10 */ 11 private String baseWhereSQL(Object obj){ 12 StringBuffer sb = new StringBuffer(); 13 Class<? extends Object> clazz = obj.getClass(); 14 Field[] fields = clazz.getDeclaredFields(); 15 try { 16 for (int i = 0; i < fields.length; i++) { 17 Field field = fields[i]; 18 field.setAccessible(true); 19 String name = field.getName(); 20 Object value = field.get(obj); 21 Class<?> type = field.getType(); 22 if(value!=null){ 23 //处理时间格式 24 if(type == Date.class){ 25 value = DateUtils.dateStr((Date) value, "yyyy-MM-dd HH:mm:ss"); 26 } 27 sb.append(name).append("=") 28 .append("'").append(value).append("'") 29 .append(" AND "); 30 } 31 } 32 } catch (IllegalArgumentException | IllegalAccessException e) { 33 e.printStackTrace(); 34 } 35 int lastIndexOf = sb.lastIndexOf(" AND "); 36 sb.delete(lastIndexOf, sb.length()); 37 return sb.toString(); 38 }
1 /** 2 * 基础更新语句 3 * 只返回属性不为空的属性和值 4 * @author: InkYi 5 * 修改时间:2016年5月11日 - 上午11:11:25<br/> 6 * 功能说明:<br/> 7 * @param obj 8 * @return >id='0', name='inkyi', sex='1' 9 */ 10 private String baseUpdateSQL(Object obj){ 11 StringBuffer sb = new StringBuffer(); 12 Class<? extends Object> clazz = obj.getClass(); 13 Field[] fields = clazz.getDeclaredFields(); 14 try { 15 for (int i = 0; i < fields.length; i++) { 16 Field field = fields[i]; 17 field.setAccessible(true); 18 String name = field.getName(); 19 Object value = field.get(obj); 20 Class<?> type = field.getType(); 21 if(value!=null){ 22 //处理时间格式 23 if(type == Date.class){ 24 value = DateUtils.dateStr((Date) value, "yyyy-MM-dd HH:mm:ss"); 25 } 26 sb.append(name).append("=") 27 .append("'").append(value).append("'") 28 .append(", "); 29 } 30 } 31 } catch (IllegalArgumentException | IllegalAccessException e) { 32 e.printStackTrace(); 33 } 34 int lastIndexOf = sb.lastIndexOf(", "); 35 sb.delete(lastIndexOf, sb.length()); 36 return sb.toString(); 37 }