Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting timestamp field as Date or Long?

I need a consensus on the practice of persisting timestamps, specifically on the pros & cons of using java.util.Date compared to using long.

Scope of this discussion:

  • Performance
  • Querying Flexibility (e.g. date range)
  • Any hazards in coding and querying
  • Portability (e.g. migration to other DB)

About myself: I consider myself to be a beginner in JPA, dabbling in it once in a while, not being able to apply it into production level projects until now. In my current project, I commit myself to use ObjectDB (embedded) through JPA calls.

like image 893
Augustus Thoo Avatar asked Mar 29 '12 09:03

Augustus Thoo


People also ask

Is it better to use timestamp or datetime?

Timestamps are also lighter on the database and indexed faster. The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.

What is timestamp in long?

The precision of a Timestamp object is calculated to be either: 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss. 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss. [fff...] and s represents the scale of the given Timestamp, its fractional seconds precision.

What should be the datatype for timestamp in Java?

toString. Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss. fffffffff , where ffffffffff indicates nanoseconds.

What is @temporal in JPA?

@Temporal is a JPA annotation that converts back and forth between timestamp and java. util. Date . It also converts time-stamp into time.


1 Answers

The following class demonstrates 3 possible methods for persisting timestamps in JPA:

@Entity
public class Timestamps {
    private java.sql.Timestamp ts1;
    private @Temporal(TemporalType.TIMESTAMP) java.util.Date ts2;
    private long ts3;
    :
}

Regarding performance and memory consumption, ts3 is a bit more efficient.

ts3 may be less convenient to use than ts1 and ts2 (in ObjectDB Database Explorer, reports, etc.).

Basic queries such as retrieval by date range are supported for all the three, but extracting date and time parts (YEAR, MONTH, etc.) in queries is not supported for ts3.

All these forms are expected to be portable.

ts1 and ts2 are practically equivalent.

More details are provided in the ObjectDB manual.

like image 141
ObjectDB Avatar answered Sep 23 '22 08:09

ObjectDB