1

please I need your help, I have been trying to add a Date field into DB using SpringBoot and JPA, but when I try to do it inserts the data in null, I mean, all other fields are recognized well using Json, but Date field in null. I have found other questions about it but I have not been able to solve it yet. I also tryied changing anotation above Date field and no luck. Any help is appreciated, thanks!

From my Entity "Member"

@JsonFormat(pattern="yyyy-MM-dd")
@Column(name = "birth_day")
private Date birth_day;

From my controller

@PostMapping()
@ResponseStatus(value = HttpStatus.CREATED)
public ResponseEntity<Member> save(@Validated @RequestBody Member input) {
    memberRepository.save(input);
    return ResponseEntity.ok().body(input);
}

This is the Json I create and pass through the body

{
    "name": "test",
    "last_name": "test",
    "phone": "test",
    "birth_day": "1991-04-05",
    "home_address": "test"
}

And this is the response I get

{
    "id": 12,
    "name": "test",
    "last_name": "test",
    "phone": "test",
    "birth_day": null,
    "home_address": "test"
 }

For what I can see, the rest of the fields created with no problem, but the field birth_day is a null DateTime in DB.

By the way I am using Mysql 5.7.22 and Java 11

8
  • Date is a broken, deprecated class. Use classes from the java.time package, like LocalDate, instead. Commented Mar 10, 2022 at 10:42
  • Ok I changed Date to LocalDate, but still it keeps inserting null data to the field birth_date Commented Mar 10, 2022 at 10:47
  • did you also tried @JsonFormat(pattern="yyyy-MM-DD") ? Commented Mar 10, 2022 at 10:54
  • That's what I used before and also no luck Commented Mar 10, 2022 at 10:57
  • I mean with uppercase DD. Commented Mar 10, 2022 at 10:58

1 Answer 1

1

The @JsonFormat for Dates annotation needs also the shape parameter as shown here. So the snippet to use is

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
@Column(name = "birth_day")
private Date birth_day;
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.