CodeMed
CodeMed

Reputation: 9201

Current datetime in Joda-Time date formatting for mysql timestamp

I need to import the current date and time into a MySQL database field whose format is TimeStamp. From examining sample data, it seems that the format for the MySQL TimeStamp datatype is "yyyy-mm-dd hh:mm:ss". I am using Joda-Time formatting in my spring hibernate application. How do I get the current date time in a format that will be accepted by the underlying MySQL TimeStamp formatted field?

Here is my current code, which will not compile because eclipse says .parseDateTime() requires a string argument and not a DateTime argument:

public void setCreated(){
    DateTime now = new org.joda.time.DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
    created = fmt.parseDateTime(now);
    System.out.println("'''''''''''''''''''''' created is: "+created);
}

The entity that I am trying to persist is defined as follows:

@Entity
@Table(name = "documents")
public class Document {
@Id
@GeneratedValue
@Column(name="id")
private Integer id;

@ManyToOne
@JoinColumn(name = "client_id")
private Patient patient;

@ManyToOne
@JoinColumn(name = "type_id")
private DocumentType type;

@Column(name="name")
private String name;

@Column(name="description")
private String description;

@Column(name="filename")
private String filename;

@Column(name="content")
@Lob
private Blob content;

@Column(name="content_type")
private String contentType;

@Column(name = "created")
private DateTime created;

public Integer getId(){return id;}
public void setId(Integer i){id=i;}

protected void setPatient(Patient patient) {this.patient = patient;}
public Patient getPatient(){return this.patient;}

public void setType(DocumentType type) {this.type = type;}
public DocumentType getType() {return this.type;}

public String getName(){return name;}
public void setName(String nm){name=nm;}

public String getDescription(){return description;}
public void setDescription(String desc){description=desc;}

public String getFileName(){return filename;}
public void setFileName(String fn){filename=fn;}

public Blob getContent(){return content;}
public void setContent(Blob ct){content=ct;}

public String getContentType(){return contentType;}
public void setContentType(String ctype){contentType=ctype;}

public void setCreated(){
    DateTime now = new org.joda.time.DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
    created = fmt.parseDateTime(now);
System.out.println("''''''''''''''''''''''''''' created is: "+created);
}
public DateTime getCreated() {return this.created;}

@Override
public String toString() {return this.getName();}
public boolean isNew() {return (this.id == null);}

}

How do I change the above so that it saves data in the correct format for insertion into a MySQL TimeStamp field?


EDIT:

Related to Sotirios' suggestion, here are relevant portions to my current pom.xml for discussion purposes:

<properties>
    <jodatime-hibernate.version>1.3</jodatime-hibernate.version>
    <jodatime-jsptags.version>1.1.1</jodatime-jsptags.version>
    <jodatime.version>2.3</jodatime.version>
    <jadira-usertype-core.version>3.1.0.CR8</jadira-usertype-core.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.jadira.usertype</groupId>
        <artifactId>usertype.core</artifactId>
        <version>${jadira-usertype-core.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>${jodatime.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time-hibernate</artifactId>
        <version>${jodatime-hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time-jsptags</artifactId>
        <version>${jodatime-jsptags.version}</version>
    </dependency>
</dependencies>

Upvotes: 2

Views: 8150

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

Because you seem like you need it:

My entity class

@Entity
@Table(name = "time_fields")
public class TimeFields {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long timeId;

    @Column
    @Temporal(TemporalType.DATE)
    private Date date;

    @Column
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime dateTime;

with appropriate getters and setters.

The client code

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PersistenceContext.class);
SessionFactory sessionFactory = context.getBean(SessionFactory.class);
Session session = sessionFactory.openSession();

TimeFields timeFields = new TimeFields();
Date date = new Date();
DateTime dateTime = new DateTime();
System.out.println(date);
System.out.println(dateTime);
timeFields.setDate(date);
timeFields.setDateTime(dateTime);

session.beginTransaction();
session.persist(timeFields);
session.getTransaction().commit();

System.out.println(timeFields.getTimeId());
System.out.println(timeFields.getDate());
System.out.println(timeFields.getDateTime());

This prints

Tue Dec 17 00:22:35 EST 2013
2013-12-17T00:22:35.843-05:00
3
Tue Dec 17 00:22:35 EST 2013
2013-12-17T00:22:35.843-05:00

Along with joda-time and hibernate, you'll need the jadira libs

<dependency>
    <groupId>org.jadira.usertype</groupId>
    <artifactId>usertype.jodatime</artifactId>
    <version>2.0.1</version>
</dependency>

You should read more about Hibernate UserTypes.

Upvotes: 4

Eric Haynes
Eric Haynes

Reputation: 5796

The string representation of a date is purely for human consumption. Timestamps are represented internally as a numeric value that is agnostic of time zones. As yyyy-mm-dd hh:mm:ss does not contain a timezone, trying to do the conversion yourself opens you up to errors with timezones.

Hibernate will handle a java.util.Date or java.sql.Date directly, so you could change the data type to one of those, and then perform the mapping to the joda object in the getter/setter so it's available that way to the callers.

Preferably, IMO, you can provide Hibernate with a mapping to joda objects. There is a library already prepared for this:

https://github.com/JodaOrg/joda-time-hibernate

or via maven:

http://mvnrepository.com/artifact/joda-time/joda-time-hibernate

NOTE: My personal rule of thumb is that if you see code manipulating dates as strings, it's broken... not a scientific metric by any means, but I find it far better than 50/50. :)

EDIT: Docs are here: http://www.joda.org/joda-time-hibernate/userguide.html

With that on the classpath, you should then be able to annotate your column like:

@Column(name = "created")
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime created;

Upvotes: 1

Related Questions