如何将多个日期映射到休眠状态并避免冗余?

时间:2016-06-23 06:55:22

标签: mysql hibernate database-design

让我们说预订可以有很多日期!我认为我的代码有点多余,因为我必须将 booking_date 插入 预订 预订 进入 booking_date

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

Booking_date:

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

我已经创建了预订实体,现在我需要在预订中插入一堆日期。首先,我必须遍历List的{​​{1}}并将我们上面创建的预订设置为每个人(我觉得可以避免这种情况)?

BookingDate

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

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

1 个答案:

答案 0 :(得分:0)

这应该是

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;

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