在我的示例中,我有两个实体要持久化。但是当我尝试使用 @MapKeyColumn 注释时,我对如何使用这个注释以及如何持久化数据感到困惑。这是“PRO JPA2 book”中解释的示例。当我尝试运行此代码时,它将生成异常。
两个实体:
@Entity
@Access(AccessType.FIELD)
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String salary;
@Enumerated(EnumType.STRING)
private EmployeeType type;
@ManyToOne
@JoinColumn(name="dept_id")
private Department deparment;
和
@Entity
public class Department {
@Id
@Column(name="dept_id")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String Name;
@OneToMany(mappedBy="deparment")
@MapKeyColumn(name="cabin_id")
private Map<String , Employee> empCabin;
......................................
public Map<String, Employee> getEmpCabin() {
return empCabin;
}
public void assignEmpToCabin(Employee emp , String cabinNo) {
System.out.println(emp+" "+cabinNo);
getEmpCabin().put(cabinNo, emp);
if(emp.getDeparment() != null){
emp.getDeparment().removeEmpFromDept(emp);
}
emp.setDeparment(this);
}
public void removeEmpFromDept(Employee emp) {
Iterator<Map.Entry<String, Employee>> entrySet = getEmpCabin().entrySet().iterator();
if(entrySet.hasNext()){
Employee current = ((Map.Entry<String, Employee>) entrySet.next()).getValue();
if(current.getId() == emp.getId()){
System.out.println("dept remove");
entrySet.remove();
current.setDeparment(null);
}
}
}
我的服务类功能
public class EmployeeService {
private EntityManager em;
.............
public void setEmpCabin(Employee emp , Department dept , String cab_id) {
dept.assignEmpToCabin(emp, cab_id);
}
我的主要代码:
tr.begin();
Department dept = deps.createDepartment("Sci");
Employee emp = es.createEmployee("Harmeet Singh", "500" , "5684", dept);
es.setEmpCabin(emp, dept, "10");
tr.commit();
当我尝试使用 setEmpCabin(...) 函数插入数据时,它会生成异常
Caused by: org.hibernate.exception.GenericJDBCException: Field 'cabin_id' doesn't have a default value