如何将主键添加到视图?

时间:2014-08-27 05:18:38

标签: java mysql sql hibernate

我希望使用Hibernate将数据库视图映射到Java对象,但由于我的视图中没有Id,所以我无法做到。

如何在视图中将列设置为主键?

@Entity
@Table(name = "employmentinformationview")
public class EmploymentInformationView implements Serializable {

    //@Id
    //No primary key

    @Column(name = "InfoID")
    private int infoId;

    @Column(name = "EmpID")
    private String empId;

    ...

}

1 个答案:

答案 0 :(得分:0)

根据Piotr的建议,选择视图中唯一的一列或一组列。如果您有一个唯一且不为null的列,则可以选择该列作为主键。

例如,要将empId作为主键,您可以尝试:

@Id
@Column(name = "EmpID")
private String empId;

但是,如果您有多个可以形成复合键的列,则需要使用@EmbeddedId创建复合键:

@Entity
@Table(name = "employmentinformationview")
public class EmploymentInformationView implements Serializable {

    @EmbeddedId
    @AttributeOverride(name="infoId", column=@Column(name="InfoID")
    @AttributeOverride(name="empId", column=@Column(name="EmpID")
    EmploymentViewId id;

    ...

}

复合键声明为Embedabble类:

@Embeddable
class EmploymentViewId implements Serializable {
    int infoId;
    String empId;
}