日期未正确插入数据库

时间:2016-10-20 14:40:44

标签: java mysql spring hibernate

我使用Spring Framework和Hibernate作为ORM工具。每当我向数据库中插入日期时,日期都没有正确插入。例如 我面临的问题是,如果我提供输入

2016年10月20日 在数据库中,它被存储为 2016/10/19。(一天的差异。)。我正在使用SimpleDateFormat格式化日期作为用户提交的表单的输入。我只想存储Date而不是TIMESTAMP。以下是我的控制器和型号代码。

package com.bbms.web.controllers;

import com.bbms.web.models.BloodBag;
import com.bbms.web.models.donor.DonorPersonalInformation;
import com.bbms.web.services.BloodBagService;
import com.bbms.web.services.DonorService;
import com.bbms.web.validators.BloodBagValidator;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping(value = "/admin/blood-bag")
public class BloodBagController {

    @Autowired
    private DonorService donorService;

    @Autowired
    private BloodBagValidator bloodBagValidator;

    @Autowired
    private BloodBagService bloodBagService;

    private BloodBag bloodBag;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        binder.registerCustomEditor(Date.class, "collectionDate", new CustomDateEditor(format, true));
        binder.registerCustomEditor(DonorPersonalInformation.class, "donor", new BloodBagController.DonorEditor());
    }

    @RequestMapping(value = "/collect-blood", method = RequestMethod.GET)
    public String collectBlood(Model model) {
        bloodBag = new BloodBag();
        bloodBag.setBloodBagId(bloodBagService.generateBloodBagNumber());
        model.addAttribute(bloodBag);
        model.addAttribute("donors", donorService.findAll());
        model.addAttribute("title", "Blood Bank : Collect Blood");
        return "bloodBag/collectBlood";
    }

    @RequestMapping(value = "/collect-blood", method = RequestMethod.POST)
    public String saveBloodBag(Model model, @Valid BloodBag bloodBag, BindingResult result,
            RedirectAttributes redirectAttributes) {
        bloodBagValidator.validate(bloodBag, result);
        if (result.hasErrors()) {
            model.addAttribute("donors", donorService.findAll());
            model.addAttribute("title", "Blood Bank : Collect Blood");
            return "bloodBag/collectBlood";
        }
        bloodBagService.saveBloodBag(bloodBag);
        redirectAttributes.addFlashAttribute("message", "Blood bag saved.");
        return "redirect:/admin/blood-bag/stock";
    }
}

模型类

package com.bbms.web.models;

import com.bbms.web.models.donor.DonorPersonalInformation;
import com.fasterxml.jackson.annotation.JsonBackReference;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "BLOOD_BAG")
public class BloodBag implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @Column(unique = true, nullable = false, updatable = false, name = "BLOOD_BAG_GENERATED_ID", length = 30)
    private String bloodBagId;
    @Temporal(TemporalType.DATE)
    @Column(name = "COLLECTION_DATE", length = 20, nullable = true)
    private Date collectionDate;
    @Column(name = "RED_CELLS", length = 100, nullable = true)
    private String redCells;
    @Column(name = "WHITE_CELLS", length = 100, nullable = true)
    private String whiteCells;
    @Column(name = "PLATELETSS", length = 100, nullable = true)
    private String platelets;
    @Column(name = "PLASMA", length = 100, nullable = true)
    private String plasma;


    //Setters and Getters

}

JSP文件是

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<div class="row">
    <div class="col-lg-12">
        <div class="ibox float-e-margins">
            <div class="ibox-title">
                <h5>Collect Blood</h5>
            </div>
            <div class="ibox-content">
                <sf:form class="form" commandName="bloodBag" method="POST">
                    <div class="row">
                        <div class="col-lg-6">
                            <c:set var="bloodBagIdHasBindError"><sf:errors path="bloodBagId"/></c:set>
                            <div class="form-group <c:if test="${!empty bloodBagIdHasBindError}" > has-error </c:if> ">
                                <sf:label path="bloodBagId" cssClass="control-label">Blood Bag Number</sf:label>
                                <sf:input path="bloodBagId" cssClass="form-control" palceholder="Blood Bag Number" />
                                <p><sf:errors path="bloodBagId" /></p>
                            </div>                    

                            <c:set var="collectionDateHasBindError"><sf:errors path="collectionDate"/></c:set>
                            <div class="form-group <c:if test="${!empty collectionDateHasBindError}" > has-error </c:if> ">
                                <sf:label path="collectionDate" cssClass="control-label">Date (yyyy/MM/dd)</sf:label>
                                <sf:input path="collectionDate" cssClass="form-control" palceholder="" />
                                <p><sf:errors path="collectionDate" /></p>
                            </div>
                            <c:set var="redCellsHasBindError"><sf:errors path="redCells"/></c:set>
                            <div class="form-group <c:if test="${!empty redCellsHasBindError}" > has-error </c:if> ">
                                <sf:label path="redCells" cssClass="control-label">Red Cells</sf:label>
                                <sf:input path="redCells" cssClass="form-control" palceholder="Red Cells" />
                                <p><sf:errors path="redCells" /></p>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <c:set var="whiteCellsHasBindError"><sf:errors path="whiteCells"/></c:set>
                            <div class="form-group <c:if test="${!empty whiteCellsHasBindError}" > has-error </c:if> ">
                                <sf:label path="whiteCells" cssClass="control-label">White Cells</sf:label>
                                <sf:input path="whiteCells" cssClass="form-control" palceholder="White Cells" />
                                <p><sf:errors path="whiteCells" /></p>
                            </div>                    
                            <c:set var="plateletsHasBindError"><sf:errors path="platelets"/></c:set>
                            <div class="form-group <c:if test="${!empty plateletsHasBindError}" > has-error </c:if> ">
                                <sf:label path="platelets" cssClass="control-label">Platelets</sf:label>
                                <sf:input path="platelets" cssClass="form-control" palceholder="Red Cells" />
                                <p><sf:errors path="platelets" /></p>
                            </div>                    
                            <c:set var="plasmaHasBindError"><sf:errors path="plasma"/></c:set>
                            <div class="form-group <c:if test="${!empty plasmaHasBindError}" > has-error </c:if> ">
                                <sf:label path="plasma" cssClass="control-label">Plasma</sf:label>
                                <sf:input path="plasma" cssClass="form-control" palceholder="Red Cells" />
                                <p><sf:errors path="plasma" /></p>
                            </div>
                            <div class="form-group">
                                <div class="" style="margin-top: 39px"> 
                                    <button class="btn btn-sm btn-info" type="submit">Save Blood Bag</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </sf:form>
            </div>
            <div class="ibox-footer">
            </div>
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:0)

您的问题可能与时区设置有关 - 请注意,您的实体应该使用LocalDate而不是Date类型,而不是新Java API(或Joda Time,如果您需要在较旧的JVM上运行应用程序)。 / p>

请检查您的数据库时区设置,可能与您的服务器设置不同。

答案 1 :(得分:0)

如果你可以使用Java8,那么最好使用LocalDate / LocalTime / LocalDateTime而不是使用Date类。

为您的项目添加compile org.hibernate:hibernate-java8:5.1.0.Final依赖项。

请注意不再使用Date课程。