简体   繁体   English

如何在视图中添加主键?

[英]How to add primary key to a view?

I wish to map a database view into a Java object using Hibernate but since I don't have an Id in my view, I can't do it. 我希望使用Hibernate将数据库视图映射到Java对象中,但是由于我的视图中没有Id,因此无法这样做。

How do I set a column in my view as a primary key? 如何在视图中将列设置为主键?

@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;

    ...

}

As suggested by Piotr, select a column or set of columns that are unique in your view. 根据Piotr的建议,选择一个或一组视图中唯一的列。 If you have a single column that is unique and not null then you can select that as your primary key. 如果您有一列唯一且不为null的列,则可以选择该列作为您的主键。

For example, to make empId as primary key, you can try this: 例如,要将empId用作主键,可以尝试以下操作:

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

But if you have multiple columns that can form as your composite key then you need to create an composite key using @EmbeddedId : 但是,如果您有多列可以作为复合键形成,那么您需要使用@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;

    ...

}

The composite key is declared as an Embedabble class: 组合键被声明为Embedabble类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM