Tuesday, December 6, 2011

Persist Joda Datetime with Eclipselink

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(){}
}

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  2. Thanks 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.

    Thks a lot.

    ReplyDelete
  3. I am glad that it worked for someone else. Feel free to translate it and thank you for including my credits.

    ReplyDelete
  4. This 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:
    @Column(name = "last_modified_time", nullable = false, columnDefinition = "TIMESTAMP", insertable = false)

    ReplyDelete