我有一个名为 Booking 的模型,它有一个持久的 DateTime 字段。但是,我不想直接与该字段交互,而是通过两个 transient 字符串字段date 和time 进行交互。问题是我不知道 Play 如何/何时将数据加载到字段中 - 它似乎没有使用我提供的构造函数,因为 DateTime 字段始终为空。
public class Booking extends Model {
@Column
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
public DateTime datetime;
public Integer duration;
@Transient
public String date = "1970-01-01";
@Transient
public String time = "00:00";
public Booking(String date, String time, Integer duration) {
this.datetime = toDateTime(date, time);
this.duration = duration;
}
public void setDate(String dateStr) {
this.date = dateStr;
this.datetime = toDateTime(dateStr, this.time);
}
public void setTime(String timeStr) {
this.time = timeStr;
this.datetime = toDateTime(this.date, timeStr);
}
public String getDate() {
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
return this.datetime.toString(format); //NullPointerException here!
}
public String getTime() {
DateTimeFormatter format = DateTimeFormat.forPattern("kk:mm");
return this.datetime.toString(format);//NullPointerException here!
}
这是 toDateTime 方法:
private DateTime toDateTime(String date, String time){
DateTimeFormatter fmt = ISODateTimeFormat.dateHourMinute();
DateTime dt = fmt.parseDateTime(date+"T"+time);
return dt;
}
最佳答案
play 使用的 JPA 使用默认的空构造函数来启动类。在您的情况下,Play 框架(我猜)创建了一个 Booking() 构造函数。 JPA 然后使用 getter 和 setter 来设置实体的属性。
也许您可以使用 JPA 中的 @PostLoad 注释。这会导致在您的持久数据加载到实体后调用带注释的方法。
更新:我提到了@PostLoad,但也许@PrePersist 是更好的选择,用于检查您的DateTime 字段是否为空,如果是这种情况,您可以将其设置为默认值。像这样:
@PrePersist
public void prePersist()
{
if(this.dateTime==null)
{
this.dateTime = toDateTime(this.date, this.time);
}
}
关于java - Play! 中的抽象模型界面ORM,如何加载 initial-data.yml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7387830/