Home > database >  Spring JPA @CreatedDate Entity column flushing out time LocalDateTime in wrong format
Spring JPA @CreatedDate Entity column flushing out time LocalDateTime in wrong format

Time:12-06

I have created an Entity column like below

@CreatedDate
@Column(name = "create_ts", nullable = false, updatable = false)
private LocalDateTime createdDate;

This is mapped to a Postgres table with column of type

timestamp(0) without time zone

Inserts are going in fine with the correct format in the table

2022-12-01 01:24:35

Upon doing a curl on the api,

curl -X GET "http://localhost:8080/api/v1/profile/111111"

the column data looks like below.

{"userId":111111,"createdDate":[2022,12,1,1,24,35],"lastModifiedDate":[2022,12,1,1,24,35]}

My application.yml below

  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
    show-sql=true:

Controller

    @GetMapping(path = "/{dsid}", produces = {APPLICATION_JSON_VALUE})
    public ResponseEntity<UserProfile> getUserProfile(@PathVariable Long dsid){

    Optional<UserProfile> userProfile = userProfService.getUserProfile(dsid);
    if (!userProfile.isPresent()) {
        logger.error("User profile not set for user with id: "   dsid);
        throw new ResourceNotFoundException("Profile", "id", dsid);
    }
    return new ResponseEntity<>(userProfService.getUserProfile(id).get(), HttpStatus.OK);

What am I doing wrong here?

CodePudding user response:

The solution was to annotate the Entity field createdDate with

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)

Response after adding annotation.

{
  "id": 123,
  "userPreference": {
    "theme": "dark",
    "landing": "myprojects",
    "projects": "112,333,222"
  },
  "createdDate": "2022-12-02 20:28:23",
  "lastModifiedDate": "2022-12-02 20:28:23"
}
  • Related