让我们说预订可以有很多日期!我认为我的代码有点多余,因为我必须将 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);
}
答案 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
列表,反之亦然。
希望这有帮助