有两张表,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配置文件解决方法:

 

 
  1. <many-to-one class="com.art.model.user.UserInfo" fetch="join" name="userInfo" >

  2. <column name="userId" unique="true"/>

  3. </many-to-one>

 

 

修改后的:

 
  1. <many-to-one class="com.art.model.user.UserInfo" fetch="join" name="userInfo" not-found="ignore">

  2. <column name="userId" unique="true"/>

  3. </many-to-one>

红色是修改的部分。意思是当对应的数据不存在时 忽略掉,用null值填充。该属性默认值:exception 。

 

注解配置解决方法:

使用hibernate 注解配置实体类的关联关系,在many-to-one,one-to-one关联中,一边引用自另一边的属性,如果属性值为某某的数据在数据库不存在了,hibernate默认会抛出异常。解决此问题,加上如下注解就可以了:

@NotFound(action=NotFoundAction.IGNORE),意思是找不到引用的外键数据时忽略,NotFound默认是exception

下面贴出hibernate 注解的实例代码

 
  1. @Entity

  2. @Table(name = "ICT_COMPUTER_LOCATION")

  3. public class IctComputerLocation {

  4. private static final long serialVersionUID = 1L;

  5.  
  6. private Integer id;

  7. /** IDC编号 */

  8. private String idcNum;

  9.  
  10. private Integer ictBaseId;

  11.  
  12. /** IctBase实体类 */

  13. private IctBase ictBase;

  14.  
  15. @Id

  16. @GeneratedValue(strategy = GenerationType.AUTO)

  17. @Column(name = "ID")

  18. public Integer getId() {

  19. return id;

  20. }

  21.  
  22. public void setId(Integer id) {

  23. this.id = id;

  24. }

  25.  
  26. @Column(name = "IDC_NUM")

  27. public String getIdcNum() {

  28. return idcNum;

  29. }

  30.  
  31. public void setIdcNum(String idcNum) {

  32. this.idcNum = idcNum;

  33. }

  34.  
  35. @Column(name = "ICT_BASE_ID")

  36. public Integer getIctBaseId() {

  37. return ictBaseId;

  38. }

  39.  
  40. public void setIctBaseId(Integer ictBaseId) {

  41. this.ictBaseId = ictBaseId;

  42. }

  43.  
  44. @ManyToOne(fetch = FetchType.LAZY)

  45. @JoinColumn(name = "ICT_BASE_ID", referencedColumnName = "ID", unique = false, nullable = false, insertable = false, updatable = false)

  46. @NotFound(action=NotFoundAction.IGNORE)

  47. public IctBase getIctBase() {

  48. return ictBase;

  49. }

  50.  
  51. public void setIctBase(IctBase ictBase) {

  52. this.ictBase = ictBase;