首页 > 代码库 > jodatime持久化hibernate jpa
jodatime持久化hibernate jpa
http://www.joda.org/joda-time-hibernate/index.html
JODA-TIME提供了一个功能更全面强大的功能组来替换JDK中的Date;
//字符串转日期
String timeString = "2006-01-26T13:30:00-06:00";
DateTime dateTime = new DateTime(timeString);
System.out.println(dateTime.toDate());
timeString = "2006-01-26";
dateTime = new DateTime(timeString);
System.out.println(dateTime);
java.sql.Timestamp setSendDate = Timestamp.valueOf("2006-01-26 13:30:00");
System.out.println(setSendDate);
//日期转字符串
org.joda.time.DateTime dateTime0 = new org.joda.time.DateTime ();
System.out.println(dateTime0);
System.out.println(dateTime0.toString("yyyy-MM-dd") + dateTime0.toString("hh:mm:ss") );
但是很多时候需要持久化日期到数据库中,比较流行的持久化框架Hibernate却并不支持JodaTime数据类型,hibernate支持的日期类型java.util.Date ,java.sql.Timestamp;
为了使jodaTime日期类型能够集成到hibernate框架中,需要加入jodaTime-hibernate ;
jodaTime-hibernate 1.3兼容 Hibernate 3.6 不支持 Hibernate 4.0;
如何获得jodaTime-hibernate?
<!-- Joda Time Library -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-hibernate</artifactId>
<version>1.3</version>
</dependency>
如何配置jodaTime-hibernate?
Hibernate mapping
Add the type
attribute to your property configuration. e.g.:
<property type="org.joda.time.contrib.hibernate.PersistentDateTime" name="dateTime"/>
Hibernate annotations
Set the type using the @org.hibernate.annotations.Type
annotation. e.g.:
@Column @Type(type="org.joda.time.contrib.hibernate.PersistentDateTime") private DateTime fromDate;
Sometimes there are multiple columns to be specified, as with PersistentDateTimeTZ
:
@Columns(columns={@Column(name="startTime"),@Column(name="startTimezone")}) @Type(type="org.joda.time.contrib.hibernate.PersistentDateTimeTZ") private DateTime startDateTime;