【发布时间】:2013-03-28 16:58:42
【问题描述】:
我正在编写一个使用 ORMLite 连接到后端数据库的应用程序。由于该应用程序将通过 VPN 运行,因此我正在尽量减少数据库调用。
为了尽量减少数据库调用,我创建了一组类来包装每个字段的值。每个包装类存储从数据库返回的原始值以及当前值。这允许诸如恢复到原始值或检查该值是否脏(即仅在一个或多个字段脏时更新数据库)之类的事情。
这对于 ORMLite 的含义是 ORMLite 在查询数据库时从不返回 null 值(即使数据库返回 null)。如果数据库中有 null 值,它会返回一个完全初始化的“包装器”,其中 currentValue 和 originalValue 变量设置为 null。
似乎这样做的正确位置是在自定义持久化器中,例如(其中StatefulIntegerProperty 是Integer 的包装器):
public class StatefulIntegerPersister extends BaseDataType {
... misc. other code
@Override
public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
Integer result = results.getInt(columnPos);
return new StatefulIntegerProperty((results.wasNull(columnPos)) ? null : result);
}
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
return sqlArg;
}
@Override
public Object javaToSqlArg(FieldType fieldType, Object obj) throws SQLException {
return ((StatefulIntegerProperty)obj).getCurrentValue();
}
@Override
public boolean isStreamType() {
return true; // this is a hack to work around ORMLite setting the value to null in the FieldType.resultToJava function
}
}
我有三个问题:
- 这是正确的方法吗?
- 在 ORMLite
FieldType.resultToJava函数中,它似乎会进行空值检查,如果数据库返回空值,它将用null替换我的包装器。现在我通过覆盖持久化器中的isStreamType方法以返回true 来解决这个问题。这是最好的方法吗?我以后会发现意外的负面影响吗? - 自定义持久化器中的
resultToSqlArg和sqlArgToJava方法有什么区别,具体来说,我应该使用其中哪一个来包装从数据库返回的值,然后我应该在其他?
【问题讨论】:
标签: ormlite