How to save an object that contains a user type field using JPA2

I am looking for a way to save an object that contains a user type field. In this particular example, I would like to save the ts field as the number of milliseconds.

import org.joda.time.DateTime; @Entity public class Foo { @Id private Long id; private DateTime ts; } 
+6
java jpa
source share
4 answers

JPA is not able to register custom property types; you will have to use provider-specific information:

+6
source share

Since this is not a supported type of JPA, you rely on implementation specifics. DataNucleus has a plugin for JodaTime that will allow you perseverance.

+1
source share

Either you can use these components of a specific provider, or use the callback methods @PostPersist , @PostUpdate , @PostLoad with the surrogate field @Transient .

http://www.java2s.com/Tutorial/Java/0355__JPA/EntityListenerPostLoad.htm will give you some insight.

Feel comfortable to get contact for further clarification.

+1
source share

One solution is to use properties other than columns and encapsulate them using getters / setters.

To tell JPA to use getters / setters instead of directly accessing private fields, you should annotate @Id on public Long getId () instead of private Long id . In doing so, just remember to use @Transient for each recipient that does not correspond directly to the column.

The following example creates a Date column named myDate , while the application will have the DateTime getTs () and setTs () methods available. (not sure about the DateTime API, so please forgive the small errors :))

 import org.joda.time.DateTime; @Entity public class Foo { private Long id; private DateTime ts; @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } // These should be accessed only by JPA, not by your application; // hence they are marked as protected protected Date getMyDate() { return ts == null ? null : ts.toDate(); } protected void setMyDate(Date myDate) { ts = myDate == null ? null : new DateTime(myDate); } // These are to be used by your application, but not by JPA; // hence the getter is transient (if it not, JPA will // try to create a column for it) @Transient public DateTime getTs() { return ts; } public void setTs(DateTime ts) { this.ts = ts; } } 
+1
source share

All Articles