使用hibernate创建视图对应的entity时,一直报 No identifier specified for entity 错。查询发现,hibernate映射表的时候entity必须有主键。
但是视图没有主键。解决办法:
给视图创建联合主键,具体操作如下:
1)创建一个包含联合主键的类,并在类上注释@Embeddable
/*** user_role视图的联合主键*/@Embeddablepublic class UserRoleCompositeId implements Serializable{ private static final long serialVersionUID = -3304319243957837925L; @Column(name = "userid") int userid; @Column(name = "sysid") int sysid; @Column(name = "sysname") String sysname; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public int getSysid() { return sysid; } public void setSysid(int sysid) { this.sysid = sysid; } public String getSysname() { return sysname; } public void setSysname(String sysname) { this.sysname = sysname; } @Override public boolean equals(Object o) { if(o instanceof UserRoleCompositeId){ UserRoleCompositeId key = (UserRoleCompositeId)o ; if(this.userid == key.userid && this.sysname.equals(key.sysname) && this.sysid==key.sysid){ return true ; } } return false ; } @Override public int hashCode() { return this.sysname.hashCode(); }}
2)在entity类中引用联合主键,并在引用上注解
@Entity@Table(name = "user_role")public class UserRoleView { @Column(name = "systype") String systype; @Column(name = "perkey") String perkey; @Id private UserRoleCompositeId userRoleCompositeId; public UserRoleCompositeId getUserRoleCompositeId() { return userRoleCompositeId; } public void setUserRoleCompositeId(UserRoleCompositeId userRoleCompositeId) { this.userRoleCompositeId = userRoleCompositeId; } public String getSystype() { return systype; } public void setSystype(String systype) { this.systype = systype; } public String getPerkey() { return perkey; } public void setPerkey(String perkey) { this.perkey = perkey; }}
问题即可得到完美解决