我从Joda Time为LocalTime
课程编写了一个自定义容器:
public class LocalTimePersister extends BaseDataType {
private static final LocalTimePersister instance = new LocalTimePersister();
private LocalTimePersister() {
super(SqlType.LONG, new Class<?>[] { LocalTime.class });
}
public static LocalTimePersister getSingleton() {
return instance;
}
@Override
public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
if (javaObject == null) {
return null;
} else {
return ((LocalTime) javaObject).millisOfDay();
}
}
@Override
public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
return results.getLong(columnPos);
}
@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
return Long.parseLong(defaultStr);
}
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
Long millis = (Long)sqlArg;
if (millis == null) {
return null;
} else {
return LocalTime.fromMillisOfDay(millis);
}
}
}
具有LocalTime
成员的类声明如下:
@DatabaseField(canBeNull = false, persisterClass = LocalTimePersister.class)
private LocalTime time;
我重新生成了我的数据库配置文件:
# --field-start--
fieldName=time
canBeNull=false
persisterClass=com.myapp.db.persisters.LocalTimePersister
# --field-end--
当我尝试创建一个具有LocalTime
字段的对象并将其添加到数据库时,我得到以下异常:
java.lang.ClassCastException: org.joda.time.LocalTime$Property cannot be cast to java.lang.Number
at com.j256.ormlite.android.AndroidDatabaseConnection.bindArgs(AndroidDatabaseConnection.java:345)
at com.j256.ormlite.android.AndroidDatabaseConnection.insert(AndroidDatabaseConnection.java:156)
at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:91)
at com.j256.ormlite.stmt.StatementExecutor.create(StatementExecutor.java:450)
at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:310)
at com.myapp.db.DBHandler.populateDB(DBHandler.java:178)
答案 0 :(得分:1)
org.joda.time.LocalTime$Property cannot be cast to java.lang.Number
我正在返回的javaToSqlArg
方法
((LocalTime) javaObject).millisOfDay()
当我应该回来时
((LocalTime) javaObject).getMillisOfDay()
millisOfDay()
返回LocalTime.Property
,getMillisOfDay()
返回int
。