package com.xxx.utils;

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; public class ModelToSQL {
private Object target; private String idName; private Object idValue; private SqlType currentType; public enum SqlType {
INSERT, UPDATE, DELETE
} public ModelToSQL(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;
}
} public ModelToSQL(Class<?> target) {
String tableName = getTableNameForClass(target);
getFields(target); 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("=?");
}
}
}
this.sqlBuffer = sqlBuffer.toString();
} /**
* 创建跟删除
*/
private void createDelete() {
String tableName = getTableName();
getFields(target.getClass());
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));
}
}
}
System.err.println("delete:\t"+sqlBuffer.toString());
this.sqlBuffer = sqlBuffer.toString();
} protected 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();
getFields(target.getClass());
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 = readField(field);
}
}
}
sqlBuffer.replace(sqlBuffer.length()-2, sqlBuffer.length()-1, " ");
if (idName == null) {
throw new RuntimeException("not found of " + target.getClass() + "'s ID");
}
sqlBuffer.append(" WHERE ").append(idName).append("=?");
param.add(idValue);
System.err.println("update:\t"+sqlBuffer.toString());
this.sqlBuffer = sqlBuffer.toString();
} /**
* 根据注解获取表名
*/
private String getTableName() {
String tableName = null;
Class<?> clazz = target.getClass();
tableName = getTableNameForClass(clazz);
return tableName;
} private String getTableNameForClass(Class<?> clazz) {
String tableName;
Table table = clazz.getAnnotation(Table.class);
if (null != table) {
tableName = table.name();
if ("".equalsIgnoreCase(tableName)) {
tableName = clazz.getSimpleName();
}
} else {
tableName = clazz.getSimpleName();
}
return tableName;
} /**
* 创建插入语句
*/
private void createInsert() {
String tableName = getTableName();
getFields(target.getClass());
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("INSERT INTO ").append(tableName).append("("); 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));
}
}
}
int length = sqlBuffer.length();
sqlBuffer.delete(length - 1, length).append(")values(");
int size = param.size();
for (int x = 0; x < size; x++) {
if (x != 0) {
sqlBuffer.append(",");
}
sqlBuffer.append("?");
}
sqlBuffer.append(")");
System.err.println("insert:\t"+sqlBuffer.toString());
this.sqlBuffer = sqlBuffer.toString();
} private List<Object> param = new Vector<Object>(); private String sqlBuffer; public List<Object> getParam() {
return param;
} public String getSqlBuffer() {
return sqlBuffer;
} public String getIdName() {
return idName;
} public Object getIdValue() {
return idValue;
} List<Field> fields = new Vector<Field>(); protected void getFields(Class<?> clazz) {
if (Object.class.equals(clazz)) {
return;
}
Field[] fieldArray = clazz.getDeclaredFields();
for (Field file : fieldArray) {
fields.add(file);
}
getFields(clazz.getSuperclass());
} //创建注解,标识该model的table名
@java.lang.annotation.Target(value = { java.lang.annotation.ElementType.TYPE })
@java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface Table {
String name() default "";
} //创建注解,标识该model的id字段
@java.lang.annotation.Target(value = { java.lang.annotation.ElementType.FIELD })
@java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface ID {
}
}

  

最新文章

  1. mac使用指南:brew的安装
  2. Struts Upload上传文件
  3. 清除UIWebView的缓存
  4. Web体系=资源+URI+表示
  5. 【mysql】之MySQL导入sql脚本错误:2006 - MySQL server has gone away
  6. 使用单调队列优化的 O(nm) 多重背包算法
  7. 奇葩json结构解析--key是数字的json处理
  8. mongo中的分页查询
  9. LNMP之Nginx
  10. LOV里的值直接引用系统里定义的值集的值,且具有值集的安全性控制
  11. x86/x64/x86_64/i386/ia32/ia64/amd/amd64 辨析
  12. 《Effective C++》继承与面对对象设计:条款32-条款40
  13. JavaScript的几种克隆(clone)方式【转】
  14. sql 根据表名查找存储过程
  15. C++ code:函数指针数组
  16. [BZOJ2238]Mst
  17. Ubuntu下CUDA8.0卸载
  18. 特别翔实的adaboost分类算法讲解 转的
  19. Replication--对发布修改的一些小总结
  20. ADO.NET Connection Pooling at a Glance

热门文章

  1. 【转】【10g SQL新特性】q-quote使用
  2. Spring基础学习笔记-Bean的基础知识
  3. webdriverAPI-Java
  4. 我的android学习经历5
  5. Fedora 24最新工作站版本之四大重要改进
  6. spark standalone模式单节点启动多个executor
  7. cocos2d ccitemimage
  8. kali linux 一些工具及命令集1(搜集DNS信息)
  9. diff函数的实现——LCS的变种问题
  10. poj 2513 Colored Sticks(欧拉路径+并检查集合+特里)
  11. [Python] spides
  12. .net core中引用webservice,并忽略https证书验证
  13. JAVA基础——编程练习(二)
  14. Linux用户管理-中
  15. Scala入门(1)Linux下Scala(2.12.1)安装
  16. java集合详解
  17. Dynamics CRM Plugin DLL恢复工具
  18. git 入门教程之紧急修复
  19. Python爬虫中文小说网点查找小说并且保存到txt(含中文乱码处理方法)
  20. DB2在dbvisualizer 客户端执行begi/end 语句块