• java反射生成ORM


    package com.wzh.jdbc;

    import java.lang.reflect.Field;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    public class JDBCTemplate<T> {

    public boolean save(final T t) {
    String simpleName = t.getClass().getSimpleName();
    System.out.println("simpleName" + simpleName);
    final StringBuffer sql = new StringBuffer();
    final Field[] fields = t.getClass().getDeclaredFields();
    sql.append("insert into tb_").append(simpleName).append("(")
    .append(fields[0].getName());
    for (int i = 1; i < fields.length; i++) {
    sql.append(",").append(fields[i].getName());
    }
    sql.append(") values(?");
    for (int i = 1; i < fields.length; i++) {
    sql.append(",?");
    }
    sql.append(")");
    System.out.println("SQL - >" + sql.toString());
    return template(new Callback<Boolean>() {
    @Override
    public Boolean doInCallback(Connection conn,
    PreparedStatement pstm, ResultSet rs) throws Throwable {
    pstm = conn.prepareStatement(sql.toString());
    int index = 1;
    for (Field field : fields) {
    if (!field.getName().equals("UserId")) {
    if (!field.isAccessible())
    field.setAccessible(true);

    //取得字段的值
    System.out.println("field get --> "+field.get(t));
    pstm.setObject(index, field.get(t));
    index++;
    }
    }
    int row = pstm.executeUpdate();
    return row != 0 ? true : false;
    }
    });
    }

    public boolean delete(Class clazz, final int id) {
    String simpleName = clazz.getSimpleName();
    System.out.println("simpleName" + simpleName);
    final String sql = "delete from tb_" + simpleName + " where id=?";
    System.out.println("SQL->" + sql);
    return template(new Callback<Boolean>() {
    @Override
    public Boolean doInCallback(Connection conn,
    PreparedStatement pstm, ResultSet rs) throws Throwable {
    pstm = conn.prepareStatement(sql);
    pstm.setObject(1, id);
    int row = pstm.executeUpdate();
    return row != 0 ? true : false;
    }
    });
    }

    public List<T> findAll(final Class clazz) {
    String simpleName = clazz.getSimpleName();
    System.out.println("simpleName->" + simpleName);
    final StringBuffer sql = new StringBuffer();
    // 构建SQL语句 select [所有字段] from tb_class.getName() where id=?
    Field[] fields = clazz.getDeclaredFields();
    sql.append("select ").append(fields[0].getName());
    for (int i = 1; i < fields.length; i++) {
    sql.append(",").append(fields[i].getName());
    }
    sql.append(" from tb_").append(simpleName);
    System.out.println("SQL - >" + sql.toString());
    return template(new Callback<List<T>>() {
    @Override
    public List<T> doInCallback(Connection conn,
    PreparedStatement pstm, ResultSet rs) throws Throwable {
    pstm = conn.prepareStatement(sql.toString());
    rs = pstm.executeQuery();
    // 返回集合对象
    List list = new ArrayList();
    ResultSetMetaData rsmd = rs.getMetaData();
    int count = rsmd.getColumnCount();
    while (rs.next()) {
    Object object = clazz.newInstance();
    // 要得到rs返回的所有字段和信息
    for (int i = 1; i <= count; i++) {
    // 循环拿到列名id
    String column = rsmd.getColumnName(i);
    Field f = clazz.getDeclaredField(column);
    if (!f.isAccessible()) {
    f.setAccessible(true);
    }
    f.set(object, rs.getObject(column));
    }
    list.add(object);
    }
    return list;
    }
    });
    }

    private Connection conn = null;

    public JDBCTemplate() {
    super();
    conn = ConnectionFactory.GetConnection();
    }

    protected interface Callback<E> {
    E doInCallback(Connection conn, PreparedStatement pstm, ResultSet rs)
    throws Throwable;
    }

    protected <E> E template(Callback<E> callback) throws DataAccessException {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
    return callback.doInCallback(conn, pstm, rs);
    } catch (Throwable e) {
    throw new DataAccessException(e);
    } finally {
    ConnectionFactory.Close(pstm, rs);
    }
    }

    /**
    * 开启事务
    * */
    public void beginTransaction() {
    try {
    conn.setAutoCommit(false);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    /**
    * 提交事务
    * */
    public void commit() {
    try {
    conn.commit();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    /**
    * 回滚事务
    * */
    public void rollback() {
    try {
    conn.rollback();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    /**
    * 关闭连接
    * */
    public void close() {
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }

  • 相关阅读:
    用自己的算法实现startsWith和endsWith功能
    随机生成4位验证码,由用户输入并验证是否输入正确,如果输入错误就生成新的验证码让用户重新输入,最多输入5次
    二分法(网上查找结果)
    模拟摇奖:从1-36中随机抽出8个不重复的数字
    冒泡排序
    输入年龄输出年龄段
    水仙花数
    百钱买百鸡
    百马百担的问题
    控制台输出九九乘法表
  • 原文地址:https://www.cnblogs.com/zhuawang/p/3343577.html
Copyright © 2020-2023  润新知