我与员工之间有一对多的关系。像这样的电话实体:
@Entity
public class Employee {
@Id
@Column(name = "EMP_ID")
private long id;
private String name;
@OneToMany(mappedBy = "owner")
private List<Phone> phones = new ArrayList<Phone>();
}
@Entity
public class Phone {
@Id
private long id;
private String phoneNumber;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OWNER_ID")
private Employee owner;
}
在我的代码中,如果我先保存电话,然后是员工:
session.save(phone);
session.save(employee);
然后我看到并插入查询以保存Employee,然后插入查询以保存Phone,然后更新查询以更新Phone表中的owner_id。
为了避免在Phone表上插入和更新,我在我的Phone实体中添加了以下映射:
@Entity
public class Phone {
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OWNER_ID", insertable=false, updatable=false)
private Employee owner;
}
现在在这种情况下,我在Employee上看到insert然后在Phone上插入,但owner_id为null。
如何在保存实体时确保owner_id不为null?我想在我的代码中保存Phone和Employee而不是其他方式。
答案 0 :(得分:0)
由于电话是子实体,因此需要员工参考才能保存。 通过使用cascadeType注释电话,您的电话将与您的员工实体一起保存。您修改过的实体将是这样的:
@Entity
public class Employee {
@Id
@Column(name = "EMP_ID")
private long id;
private String name;
@OneToMany(mappedBy = "owner",cascade = CascadeType.ALL)
private List<Phone> phones = new ArrayList<Phone>();
/*getters and setters*/
}
@Entity
public class Phone {
@Id
private long id;
private String phoneNumber;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OWNER_ID", insertable=false, updatable=false,nullable=false)
private Employee owner;
/*getters and setters*/
}
并且必须修改您的保存逻辑,如下所示:
Employee emp = new Employee();
private List<Phone> phones = new ArrayList<Phone>();
Phone phone = new Phone();
phone.setOwner(emp);
phones.add(phone);
emp.setPhones(phones);
session.save(emp);
答案 1 :(得分:0)
根据您的要求,无需使用双向。请尝试以下步骤
@ManyToOne
即可。因此,从Employee实体中删除@OneToMany
声明。 Hibernate session.save(obj)
返回Object的id。因此,首先保存电话并抓住id
然后保存员工。参见示例
session.save(phone);
long phoneOneId = phone.getId();
Phone phoneOne = new Phone();
phoneOne.setId(phoneOneId);
// You can also add another phone like phoneTwo, phoneThree, ...
List<Phone> phones = new ArrayList<Phone>();
phones.add(phoneOne);
employee.setPhones(phones);