import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.mysql.jdbc.PreparedStatement; /** * * 类名: JdbcUtils * 包名: com.hospital.test.utils * 作者: Zhangyf * 时间: 2019年3月7日 下午5:15:00 * 描述: TODO(请在此处详细描述类) * @since 1.0.0 * * 修改历史 : * 1. [2019年3月7日]新建类 by Zhangyf * * @param <T> */ public abstract class JdbcUtils<T> { private String jdbcUrl; private String user; private String password; public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(); } } public Connection getConnection() throws SQLException { return DriverManager.getConnection(jdbcUrl, user, password); } public static void free(Connection conn, Statement stmt, ResultSet rs) { try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } /** * 通过反射的方式给对象赋值 */ public static Object setValByJavaName(String javaName, Object value, Object obj) { @SuppressWarnings("rawtypes") Class c = obj.getClass(); try { Field f = c.getDeclaredField(javaName); // 取消语言访问检查 f.setAccessible(true); //给变量赋值 f.set(obj, value); } catch (NoSuchFieldException e) { System.out.println("没有对应字段"); } catch (Exception e) { e.printStackTrace(); } return obj; } /** * 根据类型来进行转换 */ private static Object changValueType(ResultSet rs, String t, int i) throws SQLException { switch (t) { case "java.math.BigInteger": return rs.getLong(rs.getMetaData().getColumnName(i)); case "java.sql.Date": return rs.getDate(rs.getMetaData().getColumnName(i)); case "java.sql.Timestamp": return rs.getTimestamp(rs.getMetaData().getColumnName(i)); case "java.lang.Integer": return rs.getInt(rs.getMetaData().getColumnName(i)); case "java.lang.Boolean": return rs.getBoolean(rs.getMetaData().getColumnName(i)); case "java.lang.Float": return rs.getFloat(rs.getMetaData().getColumnName(i)); case "java.math.BigDecimal": return rs.getBigDecimal(rs.getMetaData().getColumnName(i)); case "java.lang.Double": return rs.getDouble(rs.getMetaData().getColumnName(i)); case "java.lang.Short": return rs.getShort(rs.getMetaData().getColumnName(i)); case "java.sql.Time": return rs.getTime(rs.getMetaData().getColumnName(i)); case "[B": return rs.getString(rs.getMetaData().getColumnName(i)); default: return rs.getString(rs.getMetaData().getColumnName(i)); } } /*@SuppressWarnings("rawtypes") protected abstract Class getEntityClassType();*/ @SuppressWarnings("unchecked") public T query(String sql) throws SQLException, InstantiationException, IllegalAccessException { Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; T t = entityClass.newInstance(); Connection conn = this.getConnection(); PreparedStatement p; p = (PreparedStatement) conn.prepareStatement(sql); ResultSet rs = p.executeQuery(); int col = rs.getMetaData().getColumnCount(); while (rs.next()) { for (int i = 1; i < col; i++) { //System.out.println("name: "+rs.getMetaData().getColumnName(i) + " java-type: " + rs.getMetaData().getColumnClassName(i)+" column-type: "+rs.getMetaData().getColumnTypeName(i)); t = (T) setValByJavaName(rs.getMetaData().getColumnName(i), changValueType(rs, rs.getMetaData().getColumnClassName(i), i), t); } } p.close(); conn.close(); return t; } @SuppressWarnings("unchecked") public List<T> queryList(String sql) throws SQLException, InstantiationException, IllegalAccessException { Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; T t = entityClass.newInstance(); List<T> list=new ArrayList<>(); Connection conn = this.getConnection(); PreparedStatement p; p = (PreparedStatement) conn.prepareStatement(sql); ResultSet rs = p.executeQuery(); int col = rs.getMetaData().getColumnCount(); while (rs.next()) { for (int i = 1; i < col; i++) { //System.out.println("name: "+rs.getMetaData().getColumnName(i) + " java-type: " + rs.getMetaData().getColumnClassName(i)+" column-type: "+rs.getMetaData().getColumnTypeName(i)); t = (T) setValByJavaName(rs.getMetaData().getColumnName(i), changValueType(rs, rs.getMetaData().getColumnClassName(i), i), t); } list.add(t); } p.close(); conn.close(); return list; } }
食用方式:
public static void main(String[] args) { String sql="SELECT * FROM user WHERE user_id=2088102122524333"; JdbcUtils<UserBindInfoDO> t=new JdbcUtils<UserBindInfoDO>() {}; t.setJdbcUrl("jdbc:mysql:///epay?characterEncoding=UTF-8"); t.setUser("root"); t.setPassword("123");try { List<UserDO> user = t.queryList(sql); System.out.println(user); } catch (InstantiationException | IllegalAccessException | SQLException e) { e.printStackTrace(); } }
注意:数据库表的字段名必须要和实体类的属性名一致,数据库里面的BLOB和Text大文本字段没处理好,只是简单的用了String类型接收,后面改进
原文:https://www.cnblogs.com/zyf-yxm/p/10491433.html