是否可以在OrmLite中保留类中的枚举字段?

时间:2010-06-15 11:20:31

标签: java sqlite ormlite

我正在尝试使用OrmLite保留以下课程:

public class Field {
    @DatabaseField(id = true)
    public String name;

    @DatabaseField(canBeNull = false)
    public FieldType type;
    ...
}

FieldTypepublic enum。对应于type的字段是SQLite中的字符串(不支持枚举)。当我尝试使用它时,我得到以下异常:

INFO [main] (SingleConnectionDataSource.java:244) - Established shared JDBC Connection: org.sqlite.Conn@5224ee
Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Initialization of DAO failed; nested exception is java.lang.IllegalArgumentException: Unknown field class class enums.FieldType for field FieldType:name=type,class=class orm.Field
 at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:51)
 at orm.FieldDAO.getInstance(FieldDAO.java:17)
 at orm.Field.fromString(Field.java:23)
 at orm.Field.main(Field.java:38)
Caused by: java.lang.IllegalArgumentException: Unknown field class class enums.FieldType for field FieldType:name=type,class=class orm.Field
 at com.j256.ormlite.field.FieldType.<init>(FieldType.java:54)
 at com.j256.ormlite.field.FieldType.createFieldType(FieldType.java:381)
 at com.j256.ormlite.table.DatabaseTableConfig.fromClass(DatabaseTableConfig.java:82)
 at com.j256.ormlite.dao.BaseJdbcDao.initDao(BaseJdbcDao.java:116)
 at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:48)
 ... 3 more

那么如何告诉OrmLite,Java端的值来自enum

1 个答案:

答案 0 :(得分:42)

ORMLite可以将枚举值保留为VARCHAR enum name (default)

// this saves it as a string in the database
@DatabaseField
OurEnum ourEnum;
...
private enum OurEnum {
    FIRST,
    SECOND, ;
}

作为替代方案,您可以保存ordinal INTEGER

// this saves it as an integer in the database
@DatabaseField(dataType = DataType.ENUM_INTEGER)
OurEnum ourEnum;

虽然您可以存储序号,但建议使用VARCHAR名称版本(默认值),因为如果您在枚举中添加或删除条目,则序号值可能会发生变化。< / p>

对于这两种枚举类型,您可以指定unknownEnumName = "..." field,这有助于向前和向后兼容。如果数据库包含枚举的未知值,那么DAO返回的对象将具有此枚举值。

@DatabaseField(unknownEnumName = "FIRST")
OurEnum ourEnum;