產生此問題的原因:
有兩張表,table1和table2.產生此問題的原因就是table1裡做了關聯<one-to-one>或者<many-to-one unique="true">(特殊的多對一映射,實際就是一對一)來關聯table2.當hibernate尋找的時候,table2裡的資料沒有與table1相匹配的,這樣就會報No row with the given identifier exists這個錯.(一句話,就是資料的
現在hibernate配置可以基於xml設定檔和註解方式,這兩種方式都能發生這個異常
xml設定檔解決方案:
<many-to-one class="com.art.model.user.UserInfo" fetch="join" name="userInfo" > <column name="userId" unique="true"/></many-to-one>
修改後的:
<many-to-one class="com.art.model.user.UserInfo" fetch="join" name="userInfo" not-found="ignore"> <column name="userId" unique="true"/></many-to-one>
紅色是修改的部分。意思是當對應的資料不存在時 忽略掉,用null值填充。該屬性預設值:exception 。
註解配置解決方案:
使用hibernate 註解配置實體類的關聯關係,在many-to-one,one-to-one關聯中,一邊引用自另一邊的屬性,如果屬性值為某某的資料在資料庫不存在了,hibernate預設會拋出異常。解決此問題,加上如下註解就可以了:
@NotFound(action=NotFoundAction.IGNORE),意思是找不到引用的外鍵資料時忽略,NotFound預設是exception
下面貼出hibernate 註解的執行個體代碼
@Entity @Table(name = "ICT_COMPUTER_LOCATION") public class IctComputerLocation { private static final long serialVersionUID = 1L; private Integer id; /** IDC編號 */ private String idcNum; private Integer ictBaseId; /** IctBase實體類 */ private IctBase ictBase; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name = "IDC_NUM") public String getIdcNum() { return idcNum; } public void setIdcNum(String idcNum) { this.idcNum = idcNum; } @Column(name = "ICT_BASE_ID") public Integer getIctBaseId() { return ictBaseId; } public void setIctBaseId(Integer ictBaseId) { this.ictBaseId = ictBaseId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ICT_BASE_ID", referencedColumnName = "ID", unique = false, nullable = false, insertable = false, updatable = false) @NotFound(action=NotFoundAction.IGNORE) public IctBase getIctBase() { return ictBase; } public void setIctBase(IctBase ictBase) { this.ictBase = ictBase; }