1

I am trying to save date and times in mysql in Spring Boot. My classes are

ReservationController.java

package com.Test.controller;

import com.Test.service.ReservationService;
import com.Test.model.reservation.Reservation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Map; 

@RestController
@RequestMapping("/api")
public class ReservationController {

    @Autowired
    private ReservationService reservationservice;

    // Create a new reservation
    @RequestMapping(value = "/me/reservations", method = RequestMethod.POST)
    public ResponseEntity<Reservation> createReservation(
                @Valid @RequestBody Reservation reservation,
                UriComponentsBuilder ucb){
        int newReservationId = reservationservice.createReservation(reservation);
        HttpHeaders newHeaders = new HttpHeaders();
        newHeaders.setLocation(ucb.path("/api/me/reservations/").path(String.valueOf(newReservationId)).build().toUri());
        return new ResponseEntity<Reservation>(
                reservation, headers, HttpStatus.CREATED);
    }
}

Reservation.java

package com.Test.model.reservation;

import javax.persistence.*;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.sql.Time;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;


@Entity(name="Reservation")
@Table(name="reservation")
public class Reservation{

    @Id
    @Column(name="reservation_id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int reservationId;

    @Column(name="date_reserved")
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
    @Temporal(TemporalType.DATE)
    @NotNull
    private Date dateReserved;

    @Column(name="time_reserved_start")
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm:ss")
    @Temporal(TemporalType.TIME)
    @NotNull
    private Date timeReservedStart;

    @Column(name="time_reserved_end")
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm:ss")
    @Temporal(TemporalType.TIME)
    @NotNull
    private Date timeReservedEnd;

    public Reservation(){

    }

    public Reservation(Date dateReserved, 
            Date timeReservedStart,
            Date timeReservedEnd){
        this.dateReserved = dateReserved;
        this.timeReservedStart = timeReservedStart;
        this.timeReservedEnd = timeReservedEnd;
    }

    public Integer getReservationId(){
        return this.reservationId;
    }

    public void setDateReserved(Date dateReserved){
        this.dateReserved = dateReserved;
    }

    public Date getDateReserved(){
        return this.dateReserved;
    }

    public void setTimeReservedStart(Date timeReservedStart){
        this.timeReservedStart = timeReservedStart;
    }

    public Date getTimeReservedStart(){
        return this.timeReservedStart;
    }

    public void setTimeReservedEnd(Date timeReservedEnd){
        this.timeReservedEnd = timeReservedEnd;
    }

    public Date getTimeReservedEnd(){
        return this.timeReservedEnd;
    }
}

ReservationRepository.java

package com.Test.repository;

import com.davide.Ubgrill.model.reservation.Reservation;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param; 
import org.springframework.data.jpa.repository.Query;

import java.util.List;

@Repository("reservationRepository")
public interface ReservationRepository extends JpaRepository<Reservation, Integer>{}

ReservationService.java

package com.Test.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.Test.model.reservation.Reservation;
import com.Test.repository.ReservationRepository;

@Service
public class ReservationService{

    @Autowired
    private ReservationRepository reservationrepository;

    public int createReservation(Reservation reservation){
        Reservation newReservation = reservationrepository.save(reservation);
        reservationrepository.flush();
        return newReservation.getReservationId();
    }
}

schema.sql

create table reservation (
    reservation_id integer not null AUTO_INCREMENT,
    date_reserved date not null,
    time_reserved_start time not null,
    time_reserved_end time not null,
    primary key(reservation_id)
);

application.properties

spring.datasource.url=jdbc:mysql://localhost/ubgrillData?useSSL=false&useLegacyDatetimeCode=false
spring.datasource.username=made
spring.datasource.password=tools
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#spring.jpa.generate-ddl=true
spring.jpa.show-sql=true

spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jackson.serialization.indent_output=true

spring.jpa.properties.hibernate.jdbc.time_zone=UTC  

server.port=9090
server.ssl.enabled=false
management.port=8500
management.security.enabled=false

TestApplication.java

package com.Test;

import javax.annotation.PostConstruct;
import java.util.TimeZone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {

        @PostConstruct
        void setUTCTimezone(){
            TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        }

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

Everytime I save the the date, it saves in UTC but it always saves one day earlier. These are the results of my previous tries: This image is my making a request to the api with httpie. Request using httpie This image is Hibernate generated trace.Hibernate generated trace This image is what is saved in mysql. Mysql database My questions is thus: How do I solve this with java.util.Date/java.sql.Date? I have parts of the api that uses it (mainly jwt autentication) that works? Thanks.

4
  • 1
    try to add the timezone to your json format. @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy, timezone = "UTC)" Commented Jan 23, 2018 at 16:04
  • @corax can you please remove &useLegacyDatetimeCode=false this property from spring.datasource.url properties file and rerun-app. Commented Jan 23, 2018 at 17:36
  • mariadb.com/kb/en/library/mariadb-connector-j-130-release-notes Commented Jan 23, 2018 at 17:37
  • @DipakThoke Why do the tutorials I have read all made the mistake of adding the useLegacyDatetimeCode=false property? Commented Jan 23, 2018 at 21:18

1 Answer 1

1

Thanks to @DipakThoke and @Patrick. The answer is to add the timezone to the json format annotation.

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.