Balconsky
Balconsky

Reputation: 2244

persisting timestamp type only date without time

In my database I want save only data without time. If I use Calendar or Date type I can write:

@Column(name = "CDATE")
@Temporal(TemporalType.DATE)
Calendar cDate; // or Date cDate

but if I want use Timestamp data type, temporal annotation does not with timestamp type:

@Column(name = "CDATE")
@Temporal(TemporalType.DATE)
Timestamp cDate;

I know, that using Timestamp date type is not preferable, but I need it according to my architecture. And I dont want every time set zero values to minutes, houers and other units in my cDate. Is there any way resolve it. P.S. I use open JPA and Oracle database.

Upvotes: 3

Views: 7187

Answers (2)

kevin the kitten
kevin the kitten

Reputation: 344

In Oracle 10, you only have the DATE column type, you determine the type, either date or timestamp by setting the size in the annotation for the column on your entity class

        @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "START_DT", table="PART_DETL", nullable = false, length = 13)
    public Date getTbl1StartDt() {
        return this.tbl1StartDt;
    }

And for a date, use this...

        @Temporal(TemporalType.DATE)
    @Column(name = "START_DT", table="PART_DETL"/*, nullable = false, length = 13*/)
    public Date getTbl1StartDt() {
        return this.tbl1StartDt;
    }
    public void setTbl1StartDt(Date tbl1StartDt) {
        this.tbl1StartDt = tbl1StartDt;
    }

Upvotes: 3

evandongen
evandongen

Reputation: 2065

If you want to persist a timestamp without a time component (I assume you just want the time to be 00:00:00) you need to set the time to zero.

It doesn't stand out as a great programming example but after some searching I just converted the given Date to a Calendar and set the hour/minute/second/millisecond to zero.

private Date stripTimeFromDate(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    calendar.set(Calendar.HOUR_OF_DAY, 0);  
    calendar.set(Calendar.MINUTE, 0);  
    calendar.set(Calendar.SECOND, 0);  
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

I use this to strip parameters for a query to make sure the 'from' and 'to' parameters for a between statement don't contain a time element.

There's no annotation in JPA that does what you want as far as I know. If you set the value without the time components on your entity that will be persisted I think you'll be fine.

Upvotes: 0

Related Questions