关闭

Java基于自定义注释和反射机制实现初级通用DAO

225人阅读 评论(0) 收藏 举报
分类:

public class SdnWareDao {

    /**
     * 线程池
     */
    private static final ExecutorService threadPools = Executors.newFixedThreadPool(4);

    /**
     * 获取Entity class注释的数据库表名
     *
     * @param clazz
     * @return table name
     */
    private static String getTableName(Class<?> clazz) {
        String tableName = null;
        if (clazz.isAnnotationPresent(Table.class)) {
            Table table = clazz.getAnnotation(Table.class);
            tableName = table.value();
        }
        if (tableName == null) {
            tableName = clazz.getSimpleName();
        }
        return tableName;
    }

    /**
     * 获取属性注释的列名
     *
     * @param field 属性
     * @return column name
     */
    private static String getColumnName(Field field) {
        String colName = null;
        if (field.isAnnotationPresent(Column.class)) {
            Column column = field.getAnnotation(Column.class);
            colName = column.value();
        }
        if (colName == null) {
            colName = field.getName();
        }
        return colName;
    }

    /**
     * 判断属性是否为id
     *
     * @param field 属性
     * @return boolean
     */
    private static boolean isId(Field field) {
        boolean flag = false;
        if (field.isAnnotationPresent(Id.class)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 查询 <E> 对应数据库表所有数据
     * 
     * @param clazz Entity
     * @param sql queryString
     * @param args parameter
     * @return the result List
     */
    public static <E> List<E> getListBySome(Class<E> clazz, String sql, Object... args) {
        List<E> arrList = new ArrayList<>();
        Connection conn = DBHelper.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Field[] fields = clazz.getDeclaredFields();
        try {
            pstmt = conn.prepareStatement(sql);
            int len = (args == null) ? 0 : args.length;
            for (int i = 0; i < len; ++i) {
                pstmt.setObject(i + 1, args[i]);
            }
            rs = pstmt.executeQuery();
            while (rs.next()) {
                E ob = clazz.newInstance();
                for (Field fi : fields) {
                    fi.setAccessible(true);
                    fi.set(ob, rs.getObject(getColumnName(fi)));
                }
                arrList.add(ob);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeRes(conn, pstmt, rs);
        }
        return arrList;
    }

    /**
     * 查询所有<E>数据
     * @param clazz Entity
     * @return the result List
     */
    public static <E> List<E> getList(Class<E> clazz) {
        String sql = "select * from " + getTableName(clazz);
        return getListBySome(clazz, sql);
    }

    /**
     * 插入数据
     * 
     * @param object a persistent class
     */
    public static void persist(Object object) {
        PersistRunnable pr = new PersistRunnable(object);
        threadPools.submit(pr);
    }

    /**
     * 插入数据
     *
     * @param obj a persistent class
     * @return boolean
     */
    public static boolean save(Object obj) {
        boolean flag = false;
        Connection conn = DBHelper.getConnection();
        PreparedStatement pstmt = null;
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        sb.append("insert into ");
        sb.append(getTableName(clazz));
        sb.append(" (");
        int len = fields.length;
        int id = 0;
        for (int i = 0; i < len; ++i) {
            if (isId(fields[i])) {
                id = i;
                continue;
            }
            sb.append(getColumnName(fields[i]));
            if (i != len - 1) {
                sb.append(" , ");
            }
        }
        sb.append(") values (");
        for (int i = 1; i < len; ++i) {
            sb.append(" ? ");
            if (i != len - 1) {
                sb.append(" , ");
            }
        }
        sb.append(")");
        try {
            pstmt = conn.prepareStatement(sb.toString());
            for (int i = 0, j = 1; i < len; ++i) {
                if (i == id) {
                    continue;
                }
                fields[i].setAccessible(true);
                pstmt.setObject(j++, fields[i].get(obj));
            }
            int res = pstmt.executeUpdate();
            if (res > 0) {
                flag = true;
            }
        } catch (Exception sqle) {
            sqle.printStackTrace();
        } finally {
            DBHelper.closeRes(conn, pstmt);
        }
        return flag;
    }

    /**
     * 更新entity数据
     *
     * @param obj an entity class to update
     * @return boolean
     */
    public static boolean update(Object obj) {
        boolean flag = false;
        Connection conn = DBHelper.getConnection();
        PreparedStatement pstmt = null;
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        sb.append("update ");
        sb.append(getTableName(clazz));
        sb.append(" set ");
        int len = fields.length;
        String idName = "id";
        int id = 0;
        for (int i = 0; i < len; ++i) {
            if (isId(fields[i])) {
                id = i;
                idName = getColumnName(fields[i]);
                continue;
            }
            fields[i].setAccessible(true);
            sb.append(getColumnName(fields[i]));
            sb.append(" = ? ");
            if (i != len - 1) {
                sb.append(", ");
            }
        }
        sb.append(" where ");
        sb.append(idName);
        sb.append(" = ?");
        try {
            pstmt = conn.prepareStatement(sb.toString());
            for (int i = 0, j = 1; i < len; ++i) {
                if (i == id) {
                    continue;
                }
                fields[i].setAccessible(true);
                pstmt.setObject(j++, fields[i].get(obj));
            }
            fields[id].setAccessible(true);
            pstmt.setObject(len, fields[id].get(obj));
            int res = pstmt.executeUpdate();
            if (res > 0) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeRes(conn, pstmt);
        }
        return flag;
    }

    /**
     * 更新数据库表某几项数据
     *
     * @param sql updateString
     * @param args values
     * @return boolean
     */
    public static boolean updateSome(String sql, Object... args) {
        boolean flag = false;
        Connection conn = DBHelper.getConnection();
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0, len = args.length; i < len; ++i) {
                pstmt.setObject(i + 1, args[i]);
            }
            int res = pstmt.executeUpdate();
            if (res > 0) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeRes(conn, pstmt);
        }
        return flag;
    }

    /**
     * 删除数据库表某几条记录
     *
     * @param tableName 表名
     * @param name 属性名
     * @param value 属性值
     * @return boolean
     */
    public static boolean delete(String sql) {
        boolean flag = false;
        Connection conn = DBHelper.getConnection();
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            int res = pstmt.executeUpdate();
            if (res > 0) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeRes(conn, pstmt);
        }
        return flag;
    }

    private static class PersistRunnable implements Runnable {

        private Object obj;

        public PersistRunnable(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {
            save(obj);
        }

    }
}




/**
 * 注释Entity对应的数据库表名
 * Created by lezg on 15/11/21.
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}

/**
 * 注释Entity属性对应数据库的列名
 * Created by lezg on 15/11/21.
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    String value();
}

/**
 * id标识
 * Created by lezg on 15/11/22.
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:259795次
    • 积分:7563
    • 等级:
    • 排名:第2840名
    • 原创:510篇
    • 转载:40篇
    • 译文:0篇
    • 评论:30条
    最新评论