我有 2 张桌子。一个叫Employee,一个叫Phones,一个员工可以有多个Phone。
员工等级:
@Entity
@Table(name = "employee")
public class Employee {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
private Integer id;
@Column(name = "name", unique = true, nullable = false, length = 25)
private String name;
@OneToMany(mappedBy="owner", fetch= FetchType.EAGER, orphanRemoval=true, cascade={CascadeType.ALL})
private List<Phone> phones;
电话类:
@Entity
@Table(name = "phone")
public class Phone {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
private long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "employee_id")
private Employee owner;
@Column(name = "phone_type", nullable = false, length = 25)
private String phoneType;
@Column(name = "phone_number", nullable = false, length = 25)
private String phoneNumber;
假设我想为现有员工添加电话。我正在这样做:
Phone phone = new Phone();
phone.setOwner(employee);
phone.setPhoneNumber("999-555-0001");
phone.setPhoneType("home");
employee.getPhones().add(phone);
dao.merge(employee); // Is it possible to get this to both persist new phones and update existing phones that were changed?
鉴于 phoneSet 中的某些电话已被保留,我不确定如何合并新电话。我必须手动保留每部手机吗?一个例子将不胜感激。我研究了级联,但我似乎无法让它工作。我收到的错误是:java.lang.IllegalStateException:实体副本已分配给不同的实体。