Martin Čuka
Martin Čuka

Reputation: 18538

Hibernate dealing with Date and Time - PostgreSql

I have an entity within that entity I have 2 attributes:
dateStart - should contain only yyyy-MM-dd
timeStart - should contain only time HH:mm

I am using postgreSQL database. My table is defined like this:

CREATE TABLE xxx
(
    dateStart date,
    timeStart time without time zone
)

I mapped this table in java using hibernate like this (Date is type of java.util.Date i would like to stick with that if possible):

@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateStart;

@Temporal(TemporalType.TIME)
@DateTimeFormat(pattern = "HH:mm")
private Date dateTime;

I am using spring as well. I have a form where user can fill input which actually create this entity

<form:form method="post" class="form-horizontal" action="..." commandName="xxx">
    <form:input path="dateStart" type="date"/>
    <form:input path="timeStart" type="time"/>
    .....
    <submit button>
</form:form>

This is my controller where I actually create my entity (when user submit form)

@RequestMapping(value = "/viewSpecificTests", method = RequestMethod.POST)
public String viewSpecificTests(Model model, @Valid XXX xxx, BindingResult result) {

    if (result.hasErrors()) {
        return "createSpecificTest";
    }

    xxxService.createTable(xxx);
    return "viewSpecificTests";
}

However when I print my entity xxx.toString(). My date and time doesn't store correctly. dateStart look like this: Tue Apr 05 00:00:00 CEST 2016
dateTime look like this: Thu Jan 01 12:30:00 CET 1970

How Can I tell hibernate to persist only date / only time ? I'm stuck with this problem for so long for some reason @Temporal doesn't work for me the way I wanted.

Upvotes: 2

Views: 4631

Answers (1)

ochiWlad
ochiWlad

Reputation: 4512

I think you should just store the date as date. Then when you are retrieving your date object from the database, use a simple date format as I have illustrated.

  public void getDate(){
       Date d = new Date();//Put your date here

       SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");//use java.text.SimpleDateformat

       String newFomart = formatter.format(d);
   }

This will return string in the format that you want. All you have to do to to pass your date as I have shown. Remember to also set the format you want in the new SimpleDateFormat("String");

Upvotes: 2

Related Questions