在Hibernate Spring Boot中在MySQL中保存日期和时间

皮质

我试图在Spring Boot中在mysql中保存日期和时间。我的课是

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);
    }
}

每次保存日期时,它都会保存在UTC中,但总是会提前一天保存。这些是我以前尝试的结果:此图像是我使用httpie向api发出请求。使用httpie请求此图像是Hibernate生成的跟踪。休眠生成的跟踪该映像是保存在mysql中的映像。MySQL数据库因此,我的问题是:如何使用java.util.Date/java.sql.Date解决此问题?我有一部分使用它的api(主要是jwt自动化)有效吗?谢谢。

皮质

感谢@DipakThoke和@Patrick。答案是将时区添加到json格式注释中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章