为什么不能在ormlite中具有DataType.SERIALIZABLE的列上执行isNotNull?

时间:2014-10-16 09:43:13

标签: java android ormlite

在Android上使用ORMLite 4.48,请考虑以下用户表...

@DatabaseTable(tableName = "users")
public class User {

    @DatabaseField(columnName = Column.UUID)
    protected String uuid;

    @DatabaseField(columnName = Column.FIRST_NAME)
    protected String firstName = null;

    @DatabaseField(columnName = Column.LAST_NAME)
    protected String lastName = null;

    @DatabaseField(columnName = Column.ADDRESS, dataType = DataType.SERIALIZABLE)
    protected Address address = null;

    // ...
}

(地址类表示从lat / lon翻译的人类可读地址)

...使用以下查询...

List<User> users = getDbHelper().getDao(User.class)
                .queryBuilder()
                .where()
                .isNotNull(User.Column.ADDRESS)
                .query();

...抛出此异常:

java.sql.SQLException: Field 'address' is of data type com.j256.ormlite.field.types.SerializableType@42ac7650 which can not be compared
        at com.j256.ormlite.stmt.query.BaseComparison.<init>(BaseComparison.java:27)
        at com.j256.ormlite.stmt.query.IsNotNull.<init>(IsNotNull.java:19)
        at com.j256.ormlite.stmt.Where.isNotNull(Where.java:315)
        ...

显然,IS NOT NULL子句不能用于存储为DataType.SERIALIZABLE的字段。

通过挖掘ORMLite代码,BaseComparison构造函数检查fieldType是否具有可比性:

https://github.com/j256/ormlite-core/blob/master/src/main/java/com/j256/ormlite/stmt/query/BaseComparison.java

protected BaseComparison(String columnName, FieldType fieldType, Object value, boolean isComparison)
        throws SQLException {
    if (isComparison && fieldType != null && !fieldType.isComparable()) {
        throw new SQLException("Field '" + columnName + "' is of data type " + fieldType.getDataPersister()
                + " which can not be compared");
    }

    ...
}

显然,SerializableType.isComparable()会返回false

https://github.com/j256/ormlite-core/blob/master/src/main/java/com/j256/ormlite/field/types/SerializableType.java

@Override
public boolean isComparable() {
    return false;
}

所以,我很清楚为什么会抛出异常。但为什么不能Where.isNull()Where.isNotNull()呢?这是一个SQLite限制还是ORMLite的作者做出了这个决定?

1 个答案:

答案 0 :(得分:0)

不确定“为什么”,但是我相信“如何”是使用ForeignCollectionField而不是DatabaseField