3

我有 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:实体副本已分配给不同的实体。

4

1 回答 1

1

我认为问题可能出在 Phone 类中的连接列注释中。您正在指定一个连接列,employee_id但在 Employee 类中@Column,id 字段的注释映射到该列id

尝试更改/同步连接列:

@ManyToOne(fetch = FetchType.EAGER, targetEntity=your.package.here.Employee.class)
@JoinColumn(name = "id")
private Employee owner;

或者

雇员.java

@Id
@Column(name = "employee_id", unique = true, nullable = false)
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
private Integer id;

电话.java

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "employee_id", targetEntity=your.package.here.Employee.class)
private Employee owner;
于 2012-11-09T00:44:22.717 回答