简体   繁体   English

日期被覆盖(Spring/Hibernate)

[英]Date gets overwritten (Spring/Hibernate)

Right now I have a "bookings" table on my main page which shows information about different bookings.现在,我的主页上有一个“预订”表,显示有关不同预订的信息。 One of the fields is "Booking Date" which shows the date and time of the creation of the booking.其中一个字段是“预订日期”,它显示了创建预订的日期和时间。 But when I edit the booking it automatically gets overwritten by a new date.但是当我编辑预订时,它会自动被新日期覆盖。 How do I keep that from happening?我如何防止这种情况发生?

My Booking class我的预订舱

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

}

Relevant methods in my MainController class:我的 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";
}

The .jsp of my main page我的主页的 .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" width="100">
                            <col align="left" width="60">
                            <col align="left" width="60">
                            <col align="left" width="60">
                            <col align="left" width="60">
                            <col align="left" width="90">
                            <col align="left" width="90">
                            <col align="left" width="90">
                            <col align="left" width="100">
                            <col align="left" width="100">
                            <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>

My editBooking.jsp:我的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>

Any help is appreciated!任何帮助表示赞赏! Sorry for the long post.抱歉,帖子太长了。

EDIT: I tried changin my code to disable updating, but it still doesn't work.编辑:我尝试更改我的代码以禁用更新,但它仍然不起作用。

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

Do not use @Type(type="timestamp") for storing dates.不要使用@Type(type="timestamp")来存储日期。 In many databases timestamps are intended to track changes instead of being an ordinary date field for your application logic.在许多数据库中,时间戳旨在跟踪更改而不是应用程序逻辑的普通日期字段。 So, switch to DATETIME in the database and remove the @Type annotation, as hibernate already converts Date to the proper type.因此,切换到数据库中的 DATETIME 并删除@Type注释,因为 hibernate 已经将Date转换为正确的类型。

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM