ammf18
ammf18

Reputation: 95

Convert and save date with spring mvc

I have in spring a form with date when I enter the data in field date with datepicker and I give you save receipt the date format as follows E MMM dd HH: mm: ss Z yyyy example Mon Jun 18 00:00:00 IST 2012 The tranformo with

         SimpleDateFormat formDate = new SimpleDateFormat ("dd/MM/yyyy");
         String birthday = formDate.format (emp.getBirthday ());

Returns a string if I then do

         Emp.setBirthday (formDate.parse (birthday));

I will return it E MMM dd HH: mm: ss Z yyyy and I need it in Date dd/MM/YYYY format to save it in the database

I have the class entity employed

public class Employees  implements java.io.Serializable {
 private int employeeId;
 private String firstName;
 private String lastName;
 private Date birthday;

//getter and setter

}

and controller

@RequestMapping(value = {"/new"}, method = RequestMethod.POST)
    public String save(ModelMap modelMap, @ModelAttribute("emp") Employees emp, BindingResult result) {
            SimpleDateFormat formaDate = new SimpleDateFormat("dd/MM/yyyy");
            String birthday = formaDate.format(emp.getBirthday());

            emp.setBirthday(formaDate.parse(birthday));

            employeesServices.saveRecord(emp);
}

To save gives me the following error

Value greater than specified precision allowed for this column

I am new enspring mvc

Translated with google translate

Upvotes: 1

Views: 12143

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26572

I am assuming that your birthday field is of java.util.Date type.

Then according to the JPA specification it must be annotated with a @Temporal.

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types. The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

As you want to cut the time from your date you should:

1) use java.sql.Date as your type

private java.sql.Date birthday;

2) or add this annotation:

@Temporal(TemporalType.DATE)
private Date birthday;

Here is the snipped from the documentation for further info:

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (ie the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

Upvotes: 3

Related Questions