POJO类
POJO(Plain Ordinary Java Object)即普通Java类,具有一部分getter/setter方法的那种类就可以称作POJO。
/* POJO类,与数据库表中的字段一一对应 * 1 类名与表名一致* 2 属性与表字段一致* - 属性的名称与表字段名相同* - 属性的类型与表字段属性一致,且使用包装类型,如 Long, Integer等* 3 生成 Getter/Setter方法*/public class Student{public Integer id; public String name;public Boolean sex;public String phone;public Date birthday;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Boolean getSex() {return sex;}public void setSex(Boolean sex) {this.sex = sex;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}
自动查询记录
public List query(String sql, Class clazz) throws Exception{// 查询ResultSet rs = executeQuery(sql);// 取得MetaDataResultSetMetaData rsmd = rs.getMetaData();AfSqlMeta[] metaArray = AfSqlMeta.read(rsmd);// 构造一个List返回int numColumn = metaArray.length;List result = new ArrayList();while(rs.next()){// 将每行数据转为一个POJO对象Object pojo = clazz.newInstance();result.add(pojo);// 通过setter设置pojo的各个属性for(int i=0; i<numColumn; i++){AfSqlMeta meta = metaArray[i]; // 该列的Meta数据String value = rs.getString(i+1); // 该列的值// 根据类型提示,转成Integer, String, Boolean, Date等基本类型Object typedValue = AfSqlReflect.typedValue(ctx, meta.type, value);// 将列值设置给POJO的属性try {AfSqlReflect.setPojo(pojo, meta.label, typedValue);}catch(Exception e){// e.printStackTrace();System.out.println("** 错误: " + e.getMessage());} } }return result;}
自动插入记录
public void insert(Object pojo) throws Exception{// 解析类的信息Class clazz = pojo.getClass();AfSqlPojo po = AfSqlPojo.from(clazz);if(po.tableName == null)throw new Exception("类 " + clazz.getName() + "中缺少AFTABLE注解! 无法自动插入!");// 准备创建SQL语句AfSqlInsert insertSQL = new AfSqlInsert(po.tableName);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 根据映射关系,类的属性名 <-> 列名,拼凑SQL语句for(AfSqlColumn c : po.columns) {String fieldName = c.name; // 列名Method getter = po.findGetter(fieldName);try {Object value = getter.invoke(pojo); // 每一列的值if(value != null){if(value instanceof Boolean) {Boolean v = (Boolean)value;value = v ? "1" : "0";}else if(value instanceof Date){Date v = (Date) value;value = sdf.format(v);}insertSQL.add(fieldName, value.toString());}}catch(Exception e){}}// 执行INSERT语句String sql = insertSQL.toString();System.out.println("** INSERT SQL:" + sql);Statement stmt = conn.createStatement(); if(po.generatedKey == null){// 无自增IDstmt.execute(sql);}else{// 自增主键ID处理// 1 如果用户在插入时已经自己指定了一个值,则MySQL会使用这个值,并返回这个值// 2 如果用户在插入时未定自增主键的值,则MySQL会生成一个自增的值,并返回stmt.execute(sql,Statement.RETURN_GENERATED_KEYS);ResultSet keys = stmt.getGeneratedKeys(); if(keys.next()){// 取回自增的IDString id = keys.getString(1);try {Method setter = AfSqlReflect.findSetter(clazz, po.generatedKey);AfSqlReflect.setPojo(pojo, setter, id);}catch(Exception e){}}}}