我正在寻找一种方法来将DateTime对象和Duration作为我的值对象的一部分。
这是我的价值对象:
@DatabaseTable(tableName = DrivingRecord.TableName)
public class DrivingRecord {
public final static String TableName = "drivingRecord";
public final static String DRIVING_TASK_COLUMN_NAME = "drivingTask";
@DatabaseField(foreign = true, columnName = DRIVING_TASK_COLUMN_NAME)
private DrivingTask drivingTask;
@DatabaseField(generatedId = true)
private int id;
@DatabaseField(dataType = DataType.LONG)
private DateTime startTime;
@DatabaseField
private Duration durationOfDriving;
}
我得到以下异常:
java.lang.IllegalArgumentException: Field class org.joda.time.Duration for field FieldType:name=durationOfDriving,class=DrivingRecord is not valid for type com.j256.ormlite.field.types.LongType@41223060, maybe should be long
尝试为DateTime
创建条目时,我也遇到了同样的异常答案 0 :(得分:2)
java.lang.IllegalArgumentException: Field class org.joda.time.Duration for
field FieldType:name=durationOfDriving,class=DrivingRecord is not valid for
type com.j256.ormlite.field.types.LongType@41223060, maybe should be long
此邮件试图告诉您,您的Duration
字段durationOfDriving
与日期类型DataType.LONG
不兼容。我不确定你发布的代码是不正确的,但我认为你会尝试这样做:
@DatabaseField(dataType = DataType.LONG)
private Duration durationOfDriving;
ORMLite原生支持DateTime
,但不支持持久保存Duration
。试图强迫它成为一个长期将无法正常工作。您将不得不为Duration
定义客户持久性。
查看documentation on custom persisters了解如何启动自己的信息。
您还可以查看此答案以获取另一个示例:Is there any way to disable ORMLite's check that a field declared with DataType.SERIALIZABLE implements Serializable?
答案 1 :(得分:1)
这是显示我能够解决问题。使时间戳变长,并保存时区。现在,如果需要,我可以搜索时间戳。
@DatabaseTable(tableName = DrivingRecord.TableName)
public class DrivingRecord {
public final static String TableName = "drivingRecord";
public final static String DRIVING_TASK_COLUMN_NAME = "drivingTask";
@DatabaseField(foreign = true, columnName = DRIVING_TASK_COLUMN_NAME)
private DrivingTask drivingTask;
@DatabaseField(generatedId = true)
private int id;
@DatabaseField(dataType = DataType.LONG)
private long startTime;
@DatabaseField
private Duration durationOfDriving;
@DatabaseField(canBeNull = false, dataType= DataType.SERIALIZABLE)
private DateTimeZone timeZone;
public void setDateTime(DateTime dateTime){
this.startTime = startTime.getMillis();
this.timeZone = startTime.getZone();
}
public DateTime getDateTime(){
return new DateTime(startTime, timeZone);
}
}
答案 2 :(得分:0)
虽然JodaTime不能与ORMLite一起使用,但您可以使用与ORMLite一起使用的Java Date。 您可以在JodaTime和Date之间进行转换。
@DatabaseField
protected Date createdAt;
public static String formatDateTime(DateTime dateTime1) {
if (dateTime1 == null || dateTime1.getYear() == 0) {
return "";
}
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, ApplicationBase.AppContext.getResources().getConfiguration().locale);
Calendar calendar02 = new GregorianCalendar(dateTime1.getYear(), dateTime1.getMonthOfYear() - 1, dateTime1.getDayOfMonth());
Date date3 = calendar02.getTime();
String date3str = DataItemBase.formatDate(date3);
return date3str;
}