需要使用Map和@MapKeyColumn来了解@oneToMany

时间:2013-03-20 09:57:53

标签: java jpa jpa-2.0

这是我的sql表结构,

create table TBL_DEPARTMENT_ONE(
   ID integer primary key generated always as  identity  (start with 50, increment by 1),
   name varchar(100)
)

create table TBL_EMPLOYEE_THREE(
   ID integer primary key generated always as  identity  (start with 100, increment by 1),
   name varchar(100),
   dept_ID integer references  TBL_DEPARTMENT_ONE
)

在这里,我们在员工和部门之间建立了一对多关系的结构,其中许多员​​工可以属于一个部门,

现在,这是JPA映射代码如下, 对于员工,

@Entity
@Table(name="TBL_EMPLOYEE_THREE")
public class EmployeeEntityThree implements Serializable{
    public EmployeeEntityThree(){}

    public EmployeeEntityThree(String name,String mobileNo,DepartmentEntityOne dept){
       this.empName = name;
       this.department = dept;
       this.mobileNo = mobileNo;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID")
    private Integer employeeId;

    @Column(name="MOBILE_NO")
    private String mobileNo;

    @ManyToOne(cascade={CascadeType.PERSIST,
                        CascadeType.MERGE},
            fetch= FetchType.LAZY,targetEntity=DepartmentEntityOne.class) 
    @JoinColumn(name="DEPT_ID")
    private DepartmentEntityOne department;
    .....
    ...
}

以下代码属于部门实体,

@Entity
@Table(name="TBL_DEPARTMENT_ONE")
public class DepartmentEntityOne implements Serializable{
    public DepartmentEntityOne(){ }

    public DepartmentEntityOne(String name){
             this.deptName = name;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID")
    private Integer deptId;

    @Column(name="NAME")
    private String deptName;

    @OneToMany(cascade= {   CascadeType.MERGE, 
                                  CascadeType.PERSIST},
                   fetch= FetchType.LAZY,mappedBy="department")
    @MapKeyColumn(name="xxxxx")
    private Map<String,EmployeeEntityThree> employees;
    ...
    ..
}

这是我主要测试方法中的代码,

DepartmentEntityOne deptOne = new DepartmentEntityOne("Mechanical Engineering");
Map<String,EmployeeEntityThree> empMap = new HashMap<String,EmployeeEntityThree>();
EmployeeEntityThree[] array = new EmployeeEntityThree[]{
     new EmployeeEntityThree("Amar","9000000001",deptOne),
     new EmployeeEntityThree("Akbar","9000000002",deptOne),
     new EmployeeEntityThree("Anthony","9000000003",deptOne)
};
empMap.put(array[0].getMobileNo(),array[0]);
empMap.put(array[1].getMobileNo(),array[1]);
empMap.put(array[2].getMobileNo(),array[2]);
deptOne.setEmployees(empMap);
em = emf.createEntityManager();
em.persist(deptOne);

代码可以正常完成所有插入

现在我的问题是针对实体部门的 哪里使用了@MapKeyColumn(name =“xxxx”),其中“xxxx”是一些垃圾值, 这里应该是什么名字=? 因为在此之前它是name =“mobileNo”,它是Employee实体中的属性。 这也有效。

那么@MapKetColumn(名字=?)

的实际价值应该是什么?

1 个答案:

答案 0 :(得分:1)

您应该参考name表格的Employee列。

@MapKeyColumn(name="NAME")
private Map<String,EmployeeEntityThree> employees;