We have to create an encoder
import java.sql.Timestamp; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.sessions.Session; import org.joda.time.DateTime; public class JodaDateTimeConverter implements Converter { private static final long serialVersionUID = 1L; @Override public Object convertDataValueToObjectValue(Object dataValue, Session session) { return dataValue == null ? null : new DateTime((Timestamp) dataValue); } @Override public Object convertObjectValueToDataValue(Object objectValue, Session session) { return objectValue == null ? null : new Timestamp(((DateTime) objectValue).getMillis()); } @Override public void initialize(DatabaseMapping mapping, Session session) { } @Override public boolean isMutable() { return false; } }
Then the encoder can be used to annotate the fields:
import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @Entity public class DateToRemember { @Id @GeneratedValue(strategy = GenerationType.TABLE) private int id; @Column(columnDefinition = "TIMESTAMP") @Converter(name = "dateTimeConverter", converterClass = net.xan.taskstack.JodaDateTimeConverter.class) @Convert("dateTimeConverter") private DateTime date; }
Or the classic version:
@Entity public class DateToRemember { @Id @GeneratedValue(strategy = GenerationType.TABLE) private int id; @Column(columnDefinition = "TIMESTAMP") @Converter(name = "dateTimeConverter", converterClass = net.xan.taskstack.JodaDateTimeConverter.class) @Convert("dateTimeConverter") private DateTime date; public int getId(){return id;} public DateTime getDate(){return date;} public void setId(int id ){ this.id = id;} public void setDate(DateTime date ){ this.date = date;} public DateToRemember(){} }
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
DeleteThanks man, I Try and works for me... Really good, I would like to know if i have the permission to translate this post with your credits for my brazilian blog.
ReplyDeleteThks a lot.
I am glad that it worked for someone else. Feel free to translate it and thank you for including my credits.
ReplyDeleteThis helped me. For anyone else that wants to have nullable = false in their column definition, you might run into problems if you don't also include insertable = false also, as some databases (MySQL) might try to insert a (incorrect) value if you provide null so:
ReplyDelete@Column(name = "last_modified_time", nullable = false, columnDefinition = "TIMESTAMP", insertable = false)
how convert on the entity to DATE
ReplyDelete