2

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.

2
  • 2
    Did you check on the database how the date fields are stored? There is a difference between the values stored in the database and the object representation of the date object. Commented Apr 5, 2016 at 8:58
  • Yes, you are absolutely right. Everything make sense now. Thanks Commented Apr 5, 2016 at 10:11

1 Answer 1

2

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");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.