我有一个包含客户和预订的数据库。每个预订有1个客户,客户可以预订很多。所以我在客户成员上注明了@ManyToOne关系。我想如果删除客户,预订也将被删除。但我只能以另一种方式做到这一点,如果预订被删除,客户被删除,我不希望这样。这是我的代码:
@Entity
@NamedQueries({
@NamedQuery(name = Customer.FIND_ALL, query = "SELECT c FROM Customer c ORDER BY c.name ASC"),
@NamedQuery(name = Customer.FIND_BY_EMAIL, query = "SELECT c FROM Customer c WHERE c.email = :email")
})
@XmlRootElement
@Table(name = "customer", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
public static final String FIND_ALL = "Customer.findAll";
public static final String FIND_BY_EMAIL = "Customer.findByEmail";
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@NotNull
@NotEmpty
@Size(min = 1, max = 50)
@Pattern(regexp = "[A-Za-z\\s]+")
@Column(name = "name")
private String name;
@Entity
@NamedQueries({
@NamedQuery(name = Booking.FIND_ALL, query = "SELECT b FROM Booking b ORDER BY b.bookingDate ASC")
})
@XmlRootElement
@Table(name = "booking", uniqueConstraints = @UniqueConstraint(columnNames = {"customer", "booking_date"}))
public class Booking implements Serializable {
private static final long serialVersionUID = -1L;
public static final String FIND_ALL = "Booking.findAll";
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@NotNull
@ManyToOne(cascade = {CascadeType.REMOVE})
@JoinColumn(name = "customer")
private Customer customer;
@NotNull
@Future(message = "Bookings must be in future")
@Column(name = "booking_date")
@Temporal(value = TemporalType.DATE)
private Date bookingDate;
因此,如果我删除客户,也应删除预订。有什么想法吗?
由于
答案 0 :(得分:0)
感谢Nizet的提示。它现在正在使用下面的代码。
/* Booking class */
@NotNull
@ManyToOne
@JoinColumn(name = "customer")
private Customer customer;
/* Customer class */
@OneToMany(cascade = CascadeType.REMOVE, mappedBy = "taxi")
private Set<Booking> bookings = new HashSet<Booking>();;