JPA

Page 64

Java Persistence/ Print version

Advanced Temporal, Dates, Times, Timestamps and Calendars Dates, times, and timestamps are common types both in the database and in Java, so in theory mappings these types should be simple, right? Well sometimes this is the case and just a normal Basic mapping can be used, however sometimes it becomes more complex. Some databases do not have DATE and TIME types, only TIMESTAMP fields, however some do have separate types, and some just have DATE and TIMESTAMP. Originally in Java 1.0, Java only had a java.util.Date type, which was both a date, time and milliseconds. In Java 1.1 this was expanded to support the common database types with java.sql.Date, java.sql.Time, and java.sql.Timestamp, then to support internationalization Java created the java.util.Calendar type and virtually deprecated (almost all of the methods) the old date types (which JDBC still uses). If you map a Java java.sql.Date type to a database DATE, this is just a basic mapping and you should not have any issues (ignore Oracle's DATE type that is/was a timestamp for now). You can also map java.sql.Time to TIME, and java.sql.Timestamp to TIMESTAMP. However if you have a java.util.Date or java.util.Calendar in Java and wish to map it to a DATE or TIME, you may need to indicate that the JPA provider perform some sort of conversion for this. In JPA the @Temporal (https:/ / java. sun. com/ javaee/ 5/ docs/ api/ javax/ persistence/ Temporal. html) annotation or <temporal> element is used to map this. You can indicate that just the DATE or TIME portion of the date/time value be stored to the database. You could also use Temporal to map a java.sql.Date to a TIMESTAMP field, or any other such conversion.

Example of temporal annotation @Entity public class Employee { ... @Basic @Temporal(DATE) private Calendar startDate; ... }

Example of temporal XML <entity name="Employee" class="org.acme.Employee" access="FIELD"> <attributes> ... <basic name="startDate"> <temporal>DATE</temporal> </basic> </attributes> </entity>

64


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.