首页 > 代码库 > java 根据实体对象生成 增删改的SQL语句
java 根据实体对象生成 增删改的SQL语句
<pre name="code" class="java">import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.List; import java.util.Vector; import org.apache.commons.lang3.reflect.FieldUtils; /** * @author Gary Huang * 博客地址:http://blog.csdn.net/hfmbook/article/details/41290641 * * */ public class UpdateSql { private Object target ; private String idName ; private Object idValue ; private SqlType currentType ; public enum SqlType { INSERT, UPDATE, DELETE } public UpdateSql(SqlType sqlType, Object target) { this.target = target ; switch (sqlType) { case INSERT: currentType = SqlType.INSERT ; createInsert(); break; case UPDATE: currentType = SqlType.UPDATE ; createUpdate() ; break; case DELETE: currentType = SqlType.DELETE ; createDelete() ; break ; } } /** * 创建跟删除 * */ private void createDelete() { String tableName = getTableName() ; Field[] fields = target.getClass().getDeclaredFields() ; StringBuffer sqlBuffer = new StringBuffer() ; sqlBuffer.append("DELETE FROM ").append(tableName).append(" WHERE ") ; for(Field field : fields){ if(!Modifier.isStatic(field.getModifiers())){ ID id = field.getAnnotation(ID.class); if(null != id){ sqlBuffer.append( field.getName()).append("=?"); param.add(readField(field)); } } } this.sqlBuffer = sqlBuffer.toString(); } public Object readField(Field field ){ try { return FieldUtils.readField( field , target, true ) ; } catch (Exception e) { throw new RuntimeException( currentType.name() ,e ) ; } } /** * 创建跟新语句 * */ private void createUpdate() { String tableName = getTableName() ; Field[] fields = target.getClass().getDeclaredFields() ; StringBuffer sqlBuffer = new StringBuffer() ; sqlBuffer.append("UPDATE ").append(tableName).append(" SET ") ; for(Field field : fields){ if(!Modifier.isStatic(field.getModifiers())){ ID id = field.getAnnotation(ID.class); if(id == null){ sqlBuffer.append( field.getName()).append("=?") ; param.add( readField(field) ) ; }else{ idName = field.getName() ; idValue = http://www.mamicode.com/readField(field) ; >java 根据实体对象生成 增删改的SQL语句
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。