日期被覆盖(Spring/Hibernate)

Posted

技术标签:

【中文标题】日期被覆盖(Spring/Hibernate)【英文标题】:Date gets overwritten (Spring/Hibernate) 【发布时间】:2016-07-16 02:19:59 【问题描述】:

现在,我的主页上有一个“预订”表格,其中显示了有关不同预订的信息。其中一个字段是“预订日期”,它显示了创建预订的日期和时间。但是当我编辑预订时,它会自动被新日期覆盖。如何防止这种情况发生?

我的预订舱位

@Entity
@Table(name="booking")
public class Booking 

    @Id
    @Column(name="id")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name="R_id")
    private Restaurant restaurant;

    @Column(name="date")
    @Temporal(TemporalType.DATE)
    private Date date;

    @Column(name="start")
    private String start;

    @Column(name="duration")
    private float duration;

    @Column(name="amount_of_people")
    private int amountOfPeople;

    @Column(name="name")
    private String name;

    @Column(name="contact_preference")
    private String contactPreference;

    @Column(name="phone_number")
    private String phoneNumber;

    @Column(name="comments")
    private String comments;

    // Date that gets overwritten
    @Column(name="current_datetime")
    @Type(type="timestamp")
    private Date currentDatetime;

    @Column(name="new_date")
    @Type(type="timestamp")
    private Date newDate;

    public Long getId() 
        return id;
    

    public void setId(Long id) 
        this.id = id;
    

    public Restaurant getRestaurant() 
        return restaurant;
    

    public void setRestaurant(Restaurant restaurant) 
        this.restaurant = restaurant;
    

    public Date getDate() 
        return date;
    

    public void setDate(Date date) 
        this.date = date;
    

    public String getStart() 
        return start;
    

    public void setStart(String start)  this.start = start; 

    public float getDuration() 
        return duration;
    

    public void setDuration(float duration) 
        this.duration = duration;
    

    public int getAmountOfPeople() 
        return amountOfPeople;
    

    public void setAmountOfPeople(int amountOfPeople) 
        this.amountOfPeople = amountOfPeople;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public String getContactPreference() 
        return contactPreference;
    

    public void setContactPreference(String contactPreference) 
        this.contactPreference = contactPreference;
    

    public String getPhoneNumber()  return phoneNumber; 

    public void setPhoneNumber(String phoneNumber)  this.phoneNumber = phoneNumber; 

    public String getComments() 
        return comments;
    

    public void setComments(String comments) 
        this.comments = comments;
    

    public Date getCurrentDatetime() 
        return currentDatetime;
    

    public void setCurrentDatetime(Date currentDatetime)  this.currentDatetime = currentDatetime; 

    public Date getNewDate()  return newDate; 

    public void setNewDate(Date newDate)  this.newDate = newDate; 

    // Comparator
    public static class BookingDateComparator implements Comparator<Booking> 
        @Override
        public int compare(Booking booking1, Booking booking2) 
            if (booking1.getDate().compareTo(booking2.getDate()) == 0) 
                return booking1.getStart().compareTo(booking2.getStart());
            
            return booking1.getDate().compareTo(booking2.getDate());
        
    


我的 MainController 类中的相关方法:

@RequestMapping(value = "bookings", method = RequestMethod.GET)
public String bookings(Model model) 
    List<Booking> bookingList = bookingService.getBookings();
    model.addAttribute("bookings", bookingList);
    initModelList(model);
    return "bookings";

    @RequestMapping(value = "booking/create", method = RequestMethod.GET)
public String createBooking(Model model) 
    model.addAttribute("booking", new Booking());
    initModelList(model);
    return "newBooking";


@RequestMapping(value = "booking/create", method = RequestMethod.POST)
public String createBookingAction(@Valid @ModelAttribute ("booking") Booking booking, BindingResult result, Model model) 
    BookingFormValidator bookingFormValidator = new BookingFormValidator();
    bookingFormValidator.validate(booking, result);
    if (result.hasErrors()) 
        initModelList(model);
        return "newBooking";
    
    bookingService.addBooking(booking);
    return "redirect:/bookings";


@RequestMapping(value = "booking/edit/id", method = RequestMethod.GET)
public String editBooking(@PathVariable Long id, Model model) 
    initModelList(model);
    Booking booking = bookingService.getBooking(id);
    model.addAttribute("booking", booking);
    return "editBooking";


@RequestMapping(value = "booking/edit/id", method = RequestMethod.POST)
public String editBookingAction(@Valid @ModelAttribute ("booking") Booking booking, BindingResult result, Model model) 
    BookingFormValidator bookingFormValidator = new BookingFormValidator();
    bookingFormValidator.validate(booking, result);
    if (result.hasErrors()) 
        initModelList(model);
        return "editBooking";
    
    bookingService.updateBooking(booking);
    return "redirect:/bookings";

我的主页的.jsp

<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">

    <section class="content-wrapper main-content clear-fix">


        <h2>List of bookings</h2>

        <p>
            <a href="/restaurant/create">Add restaurant</a>
            <a href="/booking/create">Create New Booking</a>
        </p>
        <table class="">
            <tr>
                <th>
                    Booking information
                </th>
                <th></th>
            </tr>

            <c:forEach items="$restaurants" var="restaurants">
                <tr>
                    <td><h3>$restaurants</h3></td>
                    <td valign="bottom"><a href="/restaurant/edit/$restaurants.id">Edit restaurant</a></td>

                    <tr>
                        <table>
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <col align="left" >
                            <tr>
                                <td align="left"><b>Date</b></td>
                                <td align="left"><b>Start</b></td>
                                <td align="left"><b>Duration</b></td>
                                <td align="left"><b># Of People</b></td>
                                <td align="left"><b>Name</b></td>
                                <td align="left"><b>Contact Pref.</b></td>
                                <td align="left"><b>Phone #</b></td>
                                <td align="left"><b>Comments</b></td>
                                <td align="left"><b>Booking date</b></td>
                            </tr>
                            <c:forEach items="$sortedBooking" var="sortedBooking">
                                <c:choose>
                                    <c:when test="$restaurants == sortedBooking.restaurant.restaurantName">
                                        <tr>
                                            <td>$sortedBooking.date</td>
                                            <td>$sortedBooking.start</td>
                                            <td>$sortedBooking.duration</td>
                                            <td>$sortedBooking.amountOfPeople</td>
                                            <td>$sortedBooking.name</td>
                                            <td>$sortedBooking.contactPreference</td>
                                            <c:choose>
                                                <c:when test="$sortedBooking.phoneNumber.equals('')">
                                                    <td>NO PHONE</td>
                                                </c:when>
                                                <c:otherwise>
                                                    <td>$sortedBooking.phoneNumber</td>
                                                </c:otherwise>
                                            </c:choose>
                                            <c:choose>
                                                <c:when test="$sortedBooking.comments.equals('')">
                                                    <td>NO COMMENTS</td>
                                                </c:when>
                                                <c:otherwise>
                                                    <td>$sortedBooking.comments</td>
                                                </c:otherwise>
                                            </c:choose>
                                            <td>$sortedBooking.currentDatetime</td>
                                            <td><a href="/booking/edit/$sortedBooking.id">Edit booking</a></td>
                                        </tr>
                                    </c:when>
                                </c:choose>
                            </c:forEach>
                        </table>
                    </tr>
                </tr>
            </c:forEach>
        </table>

    </section>
</div>
<jsp:include page="../fragments/footer.jsp"/>

</body>

我的editBooking.jsp:

<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">
    <section class="content-wrapper main-content clear-fix">

        <h2>Edit</h2>

        <form:form modelAttribute="booking">
            <table>
                <tr>
                    <td>Restaurant*:</td>
                    <td><form:select path="restaurant.id">
                            <form:option value="" label="--- Select ---" />
                            <form:options items="$restaurants" itemValue="id" itemLabel="restaurantName" />
                    <td><form:errors path="restaurant.id" cssClass="error"/></td>
                    </form:select>
                </tr>
                <tr>
                    <td>Date*:</td>
                    <td><form:input path="date" type="date"/></td>
                    <td><form:errors path="date" cssClass="error"/></td>
                </tr>
                <tr>
                    <td>Starting time*:</td>
                    <td><form:input path="start" type="time"/></td>
                    <td><form:errors path="start" cssClass="error"/></td>
                </tr>
                <tr>
                    <td>Duration*:</td>
                    <td><form:input path="duration"/></td>
                    <td><form:errors path="duration" cssClass="error"/></td>
                </tr>
                <tr>
                    <td>Amount of people*:</td>
                    <td><form:input path="amountOfPeople"/></td>
                    <td><form:errors path="amountOfPeople" cssClass="error"/></td>
                </tr>
                <tr>
                    <td>Name*:</td>
                    <td><form:input path="name"/></td>
                    <td><form:errors path="name" cssClass="error"/></td>
                </tr>
                <tr>
                    <td>Contact preference*:</td>
                    <td><form:select path="contactPreference">
                            <form:option value="" label="--- Select ---" />
                            <form:option value="e-mail" label="E-mail" />
                            <form:option value="phone" label="Phone" />
                            <form:option value="other" label="Other" />
                    <td><form:errors path="contactPreference" cssClass="error"/></td>
                    </form:select>
                </tr>
                <tr>
                    <td>Phone number:</td>
                    <td><form:input path="phoneNumber"/></td>
                    <td><form:errors path="phoneNumber" cssClass="error"/></td>
                </tr>
                <tr>
                    <td>Comments:</td>
                    <td><form:textarea path="comments" rows="5" cols="30"/></td>
                    <td><form:errors path="comments" cssClass="error"/></td>
                </tr>
                <tr>
                    <td colspan="3"><input type="submit" /></td>
                </tr>
            </table>
        </form:form>
        <div>
            <a href="/bookings">Back to List</a>
        </div>


    </section>
</div>
<jsp:include page="../fragments/footer.jsp"/>

</body>

感谢任何帮助!抱歉,帖子太长了。

编辑:我尝试更改我的代码以禁用更新,但它仍然不起作用。

@Column(name="current_datetime", updatable=false, nullable=false)
@Type(type="timestamp")
private Date currentDatetime = new Date();

【问题讨论】:

editBookingAction做什么?是否保存或更新?你确定它没有创造新记录吗?你能试着用@CreationTimestamp注释你的日期吗? 【参考方案1】:

不要使用@Type(type="timestamp") 来存储日期。在许多数据库中,时间戳旨在跟踪更改,而不是作为应用程序逻辑的普通日期字段。因此,在数据库中切换到 DATETIME 并删除 @Type 注释,因为 hibernate 已经将 Date 转换为正确的类型。

另请参阅:

Should I use field 'datetime' or 'timestamp'? When to use datetime or timestamp

【讨论】:

以上是关于日期被覆盖(Spring/Hibernate)的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC+Spring+Hibernate个人家庭财务管理系统

[转]Struts2+Spring3+Hibernate4+Maven+EasyUI整合入门视频+视频教程源码

即使驱动程序类名和休眠方言的值错误,Spring Hibernate 集成示例也会执行

SSH(struts2+spring+hibernate)三大框架整合

SQL 中高效的“查找最近的数字或日期”,其中日期/数字列被索引覆盖

spring hibernate lock是否适用于不同机器上的其他线程?