@Override
public void update(Object t) {
//实体类
Class entityClass = t.getClass();
//实体元数据
EntityMetaData entityMetaData = getEntityMetaData(entityClass);
//列名字段对应Map
Map<String, Field> columnFieldMap = entityMetaData.getColumnNameFieldMap();
//参数列表
List<Object> argumentList = new LinkedList<Object>();
//有值的字段名称列表(不包括主键)
List<String> hasValueColumnNameList = new LinkedList<String>();
for (String columnName : columnFieldMap.keySet()) {
//如果是主键
if (columnName.equals(entityMetaData.getPrimaryKey())) {
continue;
}
Field field = columnFieldMap.get(columnName);
try {
Object value = field.get(t);
if (value == null) {
continue;
}
hasValueColumnNameList.add(columnName);
argumentList.add(value);
} catch (Exception ex) {
}
}
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(dialect.addIdentifierSeparatingChar(entityMetaData.getTableName())).append(" SET ");
for (int i = 0; i <= hasValueColumnNameList.size() - 1; i++) {
String columnName = hasValueColumnNameList.get(i);
if (i != 0) {
sb.append(", ");
}
sb.append(dialect.addIdentifierSeparatingChar(columnName)).append(" = ?");
}
sb.append(" WHERE ").append(dialect.addIdentifierSeparatingChar(entityMetaData.getPrimaryKey())).append(" = ?;");
//添加主键的值
argumentList.add(entityMetaData.getPrimaryKeyValue(t));
String sql = sb.toString();
int rowCount = this.executeUpdate(sql, argumentList, null);
if (rowCount <= 0) {
throw new DataAccessException("更改的数据行数为0!");