Question

I would like to persist an instance of my class into objectdb.

@Entity
public class MyClazz {
  @Column(nullable = false)
  DateTime date;
}

With hibernate I just need to annotate the field with an additional annotation.

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")

But since I want to use objectdb I can't use these annotation, so I get an exception ("Attempt to store an instance of a non persistable type org.joda.time.DateTime")

The problem is that objectdb disables the "support" for serializable types. (see here) I'm pretty sure that they do this for a good reason so want to keep it this way.

As a workaround for now I use a pre and post hook.

@Column(nullable = false)   
private Date date = new Date();

@Transient
private DateTime dateTime;

@PrePersist
private void persist() {
    date = dateTime.toDate();
}

@PostLoad
private void load() {
    dateTime = new DateTime(date.getTime());
}

My question: is there another way? I would like to get rid of the additional date field.

Was it helpful?

Solution

I'm pretty sure that they do this for a good reason so want to keep it this way.

Yea. When you save a serialized object in a database, your queries won't be able to perform any tests on the object; e.g. test whether one date is later than another one. In addition, you are making your application vulnerable to the problem of incompatible serial versions. (That's probably not an issue in this specific example, but the issue comes up repeatedly in SO questions ...)

My question: is there another way? I would like to get rid of the additional date field.

Unfortunately, I don't think there is.

OTHER TIPS

In Joda, a DateTime is an instant in the same way that the Java API Date is an instant. The major difference between the two is that Date is not immutable.

Since both types are wrappers around a long integer that represent the number of milliseconds that have elapsed since Jan 1, 1970 UTC one alternative for you is to simply not persist the DateTime at all, but rather simply persist the long integer that it wraps instead.

Here is an excerpt from the Joda Javadoc:

Internally, the class holds two pieces of data. Firstly, it holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. Secondly, it holds a Chronology which determines how the millisecond instant value is converted into the date time fields. The default Chronology is ISOChronology which is the agreed international standard and compatible with the modern Gregorian calendar.

As long as the Chronology used by your application is constant or always known, you can easily regenerate the DateTime from the long integer field with:

DateTime dt = new DateTime(longInstantFieldInMillis, myChronology);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top