gpt4 book ai didi

mysql - 如何在 hibernate 状态下将多个日期映射到预订并避免冗余?

转载 作者:行者123 更新时间:2023-11-29 20:51:44 25 4
gpt4 key购买 nike

我们可以说一次预订可以有多个日期!我认为我的代码有点多余,因为我必须将 booking_date 插入 booking预订booking_date

采用以下结构,预订可以附加 1 个或多个日期(在这种情况下,对您来说可能没有多大意义。)

预订日期:

@Entity
@Table(name="booking_date")
public class BookingDate {

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

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name="start_date")
private Date startDate;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name="end_date" )
private Date endDate;

@ManyToOne
@JoinColumn(name = "booking_id")
private Booking booking;

预订:

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

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="booking_id")
private int bookingId;

// One booking to one booking date...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "booking")
private BookingDate bookingDate;

我认为我在这里做错了,因为当我将预订插入数据库时​​,我必须将预订插入到 booking_date 中,反之亦然。

让我们从我的代码中取出以下示例...插入具有多个日期的预订。

@RequestMapping(value="create/booking", method=RequestMethod.POST,  produces = {MediaType.APPLICATION_JSON_VALUE })
Booking bookingCreate(@RequestBody BookingContext bookingcont, BindingResult bindingResult) {

Booking booking = new Booking();

我已经创建了预订实体,现在我需要在该预订中插入一堆日期。首先,我必须循环遍历 BookingDateList 并将我们上面创建的预订设置为每个(我觉得这是可以避免的)?

List<BookingDate> bookingDates = <Pretend this is a list of BookingDate objects>
// Loop through bookingdates and assign the booking obj to each of them
for (BookingDate bookingDate : bookingDates) {
bookingDate.setBookingDate(bookingDate);
}

然后我会将 bookingDates 对象分配给我们的预订对象:

booking.setBookingDate(bookingDates); // Insert multiple booking dates for the booking

最佳答案

事情应该是这样的

Booking booking = new Booking();
//setting data in booking
List<BookingDate> bookingDates = <Pretend this is a list of BookingDate objects>
booking.setBookingDate(bookingDates);
session.save(booking);

这应该起作用的原因是因为预订中有Cascade.ALL,因此保存booking应该保存关联的bookingdate

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "booking")
private BookingDate bookingDate;

此外,您不需要在每个 bookingdate 中设置 booking,因为级联来自 booking 而不是来自 bookingdate因此,booking 需要知道存在 bookingdate 列表,反之亦然。希望这有帮助

关于mysql - 如何在 hibernate 状态下将多个日期映射到预订并避免冗余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37984277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com