原由
项目使用了一个数据库工具库,保存数据方法传递的是对象。项目接口调整新增了字段,本地订单保存到数据库的时候保存失败,是因为没有新增字段所在的列。就这个问题查看了一下数据库工具库源码分析问题并且解决问题。
源码分析
1、查看saveOrUpdate方法,这个方式是用来保存或者更新数据的。
@Override
public void saveOrUpdate(Object entity) throws DbException {
try {
beginTransaction();
if (entity instanceof List) {
List<?> entities = (List<?>) entity;
if (entities.isEmpty()) return;
TableEntity<?> table = this.getTable(entities.get(0).getClass());
table.createTableIfNotExists();
for (Object item : entities) {
saveOrUpdateWithoutTransaction(table, item);
}
} else {
//因为保存的对象不是集合,所以重点代码在这一块
//1. 这里是获取表实体,也就是表的名称和表中列的集合等内容
TableEntity<?> table = this.getTable(entity.getClass());
//2. 看方法名称就可以看出这个方法是在表不存在的时候创建表
table.createTableIfNotExists();
//3. 这里就是保存和更新数据的地方了
saveOrUpdateWithoutTransaction(table, entity);
}
setTransactionSuccessful();
} finally {
endTransaction();
}
}
1.1 来看一下上面方法中注释 1 的代码getTable方法中的内容
public <T> TableEntity<T> getTable(Class<T> entityType) throws DbException {
synchronized (tableMap) {
//先从缓存tableMap获取table
TableEntity<T> table = (TableEntity<T>) tableMap.get(entityType);
if (table == null) {
try</