1.获取pojo的所有属性字段,用于拼接sql语句.反射常用三种方式:
获取class对象的三种方法: 1.class.forName(...) 2.类名.class 3.对象.getClass代码案例:
Field[] fields = tClass.getDeclaredFields(); //拼接属性名 String cs = ""; String wh = ""; for (Field field : fields) { //如果这个field有NoSink这个注解,则不要拼接到sql中 NoSink noSink = field.getAnnotation(NoSink.class); if (noSink == null) { cs += field.getName() + ","; wh += "?,"; } } //insert into t(id,name,age)values(?,?,?) StringBuilder sql = new StringBuilder(); sql .append("insert into ") .append(table) .append("(") //拼接字段 .append(cs, 0, cs.length() - 1) .append(")values(") //拼接占位符 .append(wh, 0, wh.length() - 1) .append(")"); System.out.println(sql.toString()); return getJdbcSink(driver, url, sql.toString());
TODO: 2021/12/1 给sql中的占位符进行赋值,根据sql语句来实现 //获取class对象的三种方法: class.forName(...) 类名.class 对象.getClass Field[] fields = t.getClass().getDeclaredFields(); for (int i = 0, position = 1; i < fields.length; i++) { Field field = fields[i]; NoSink noSink = field.getAnnotation(NoSink.class); if (noSink == null) { //设置权限 field.setAccessible(true); Object value = field.get(t); ps.setObject(position++, value); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)