复合键在java中加入hibernate

时间:2014-06-14 10:18:31

标签: java hibernate

我正在使用hibernate来保留两个表,ProjectDepartment

Department表有一个复合主键DeptCompID

    @Embeddable
    public class DeptCompID implements Serializable
    {

        @Column(name = "DeptID")
        private int DeptID;

        @Column(name = "RoleID")
        private int RoleID;

        //getters and setters
    }

@Entity
public class Department implements Serializable
{

    @EmbeddedId 
    private DeptCompID id;

     private String name;

    @OneToOne(mappedBy="department",targetEntity = Project.class)
    private Project pro;

    //getters and setters
}

@Entity
public class Project 

{
    @Id
    private int ProId;


    @OneToOne(targetEntity = Department.class)
    @MapsId("DeptID")
    @JoinColumns({    
    @JoinColumn(name = "RoleID", referencedColumnName = "RoleID"),
    @JoinColumn(name = "DeptID", referencedColumnName = "DeptID")
    })
     private Department department;

//getters and setters
}

保留表格的代码

            Department department = new Department();
            department.setName("HR");
            DeptCompID cpk=new DeptCompID();
            cpk.setRoleID(10);
            cpk.setDeptID(60);
            department.setId(cpk);

            Project pro=new Project();
            pro.setDepartment(department);
            pro.setProId(10);
            department.setPro(pro);
            session.save(department);
            session.save(pro);

每次我坚持表项目和部门时,DeptID表中的Project列始终为空,应为60。 为什么@MapsId("DeptID")不起作用?有些人可以提供解决方案。

0 个答案:

没有答案