Chinnu's Chinnu's - 5 months ago 38
SQL Question

@DateTimeFormatter without leading zero's just yyyy-MM-dd as My SQL Spring Boot

I am working with sql db in spring boot application.
1)sql type DATE and format yyyy-MM-DD.

2)when I used Temporal type, it pulls data in proper format, but while doing edit and add operations, it doesn't seem to allow.

3)when I used DateTime formatter, everything operation works fine, but data pulls up, or being added with leading zero's in application which i don't want for my application.
Employee.java

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name="birth_date")
@NotNull @Past
// @Temporal(TemporalType.DATE)
private Date birthDate;



@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name="hire_date")
@NotNull
// @Temporal(TemporalType.DATE)
private Date hireDate;


please advise what can be done, and to add when I change type to LocalDate, it throws

There was an unexpected error (type=Internal Server Error, status=500).
could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize

Answer

Adding Joda dependencies would work, since it support Locale Date conversion and mapping would be appropriate as per sql, and will be mapped as DATE (on MySQL), i.e. only date without timestamp/leading zero's just YYYY-MM-DD. Add these in this in pom.xml

      <dependency>
   <groupId>joda-time</groupId>
   <artifactId>joda-time</artifactId>
</dependency>

<dependency>
  <groupId>org.jadira.usertype</groupId>
  <artifactId>usertype.core</artifactId>
  <version>3.1.0.CR1</version>
 </dependency>

<dependency>
   <groupId>joda-time</groupId>
   <artifactId>joda-time-hibernate</artifactId>
    <version>1.3</version>
</dependency>
<dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time-jsptags</artifactId>
       <version>1.1.1</version>
 </dependency>

and this to your entity class.

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name="birth_date")
@NotNull
private LocalDate birthDate;`   

public LocalDate getBirthDate() {
    return this.birthDate;
}

public void setBirthDate(LocalDate birthDate) {
    this.birthDate = birthDate;
}`
Comments