博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 根据实体对象生成 增删改的SQL语句 ModelToSQL
阅读量:5120 次
发布时间:2019-06-13

本文共 6375 字,大约阅读时间需要 21 分钟。

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 param = new Vector(); private String sqlBuffer; public List getParam() { return param; } public String getSqlBuffer() { return sqlBuffer; } public String getIdName() { return idName; } public Object getIdValue() { return idValue; } List
fields = new Vector
(); 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 { }}

  

转载于:https://www.cnblogs.com/firstdream/p/10089425.html

你可能感兴趣的文章
AS3优化性能笔记二
查看>>
wpf combobox
查看>>
Java高阶回调,回调函数的另一种玩法
查看>>
WCF公开服务元数据方式
查看>>
2014蓝桥杯问题 C: 神奇算式
查看>>
ElasticSearch(站内搜索)
查看>>
Node.js简单介绍并实现一个简单的Web MVC框架
查看>>
Linux压缩与解压缩
查看>>
哈希(Hash)与加密(Encrypt)相关内容
查看>>
4----COM:a Generative Model for group recommendation(组推荐的一种生成模型)
查看>>
UVA 11137 - Ingenuous Cubrency
查看>>
js阻止事件冒泡的两种方法
查看>>
Java异常抛出
查看>>
CGRect知多少
查看>>
Android 开发环境安装配置手册
查看>>
Qt工程文件说明
查看>>
[SQL Server 系] T-SQL数据库的创建与修改
查看>>
WIN7下搭建CORDOVA环境
查看>>
74HC164应用
查看>>
变量声明和定义的关系
查看>>