I have a model called Booking which has a persistent DateTime field. However I do not want to interact directly with this field, but rather through two Transient String fields, date and time. The problem is that I have no idea how/when play loads the data into the fields – it doesn’t seem to be using the constructor I provide because the DateTime field is always null.
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!
}
here’s the toDateTime method:
private DateTime toDateTime(String date, String time){
DateTimeFormatter fmt = ISODateTimeFormat.dateHourMinute();
DateTime dt = fmt.parseDateTime(date+"T"+time);
return dt;
}
It appears that you can define a default constructor that takes no parameters to set up your object when JPA loads it. Like so:
Now the only problem is that it uses the same setters I’ve defined when retrieving from the database: *Caused by: java.lang.IllegalArgumentException: Invalid format: “ISO8601:2011-08-25T02:00:00+0200…”
*