Current datetime in Joda-Time date formatting for mysql timestamp

ⅰ亾dé卋堺 提交于 2019-12-06 10:29:25

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.

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!