1

So I have an

<input type=date" > 

in my form, and the User model that has

 @Column(name=birthday)
 public Date birthday; 

Date being imported from java.util.Data

This needs to be persisted to a MySQL database, which has the following format. MySQL field is of type Date

yyyy-mm-dd

I tried changing the format using of the column

@DateTimeFormat(pattern = "yy-MMMM-dd")

but it doesn't work, I'm assuming because of the input type format. How do I change this? I am using spring-boot.

2
  • Hi! Could you provide more details? If you are using spring boot which framework you have chosen to work with MySQL: Hibernate, Spring Data JPA, Spring JDBC template? Also please provide structure of MySQL table Commented Aug 29, 2017 at 17:30
  • Hey! Of course. I'm using Spring Data JPA. CREATE TABLE user( user_id int(11) NOT NULL AUTO_INCREMENT, email varchar(255) NOT NULL, last_name varchar(255) NOT NULL, name varchar(255) NOT NULL, password varchar(255) NOT NULL, birthday Date NOT NULL, ` PRIMARY KEY` (user_id) ) Commented Aug 29, 2017 at 18:01

1 Answer 1

1

I think you have problem with MessageConvertor you should define correct date format for Jackson ObjectMapper for that you should add these two beans

@Bean
public MappingJackson2HttpMessageConverter primaryMessageConverter(){

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(getObjectMapper());
    return converter;
}

@Bean
public ObjectMapper getObjectMapper(){
    ObjectMapper objectMapper = new ObjectMapper();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    objectMapper.setDateFormat(df);
    return objectMapper;
}

After that simple rest controller should work fine

@RestController
public class UserController {

   @Autowired
   private UserRepository userRepository;

   @RequestMapping(value = "/user/",method = RequestMethod.POST)
   public ResponseEntity saveUser(@RequestBody User user) {
       userRepository.save(user);
       return ResponseEntity.status(HttpStatus.CREATED).build()
   }
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! But what I found working for me is adding these annotations on my entity, now it works. @Column(name = "birthday") @DateTimeFormat(pattern = "yyyy-MM-dd") @Temporal(TemporalType.DATE) private Date birthDate; But thank you so much!

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.