# [Hibernate] 使用 @ManyToOne 報錯 EntityNotFoundException [TOC] ## 狀況說明與解決 >javax.persistence.EntityNotFoundException: Unable to find com.test.entity.type with id 0 在使用 `@ManyToOne` 和 `@OneToOne` 時,若在關聯另一張表取無資料會報異常。如果要讓主表沒有關連到對應資料也能正常取值,需要加上 `@NotFound(action=NotFoundAction.IGNORE)` 以略過錯誤。如下: ```=java! @OneToOne @JoinColumn(name = "type_id") @NotFount(action=NotFountAction.IGNORE) private Type type; ``` 如此一來當關聯的表查無資料時,在主表的 type_id 欄位(也就是這個 model 的 type)值為 null 就不會報錯了。 參考資料: [[JPA错误]javax.persistence.EntityNotFoundException: Unable to find xxx](https://blog.csdn.net/yztezhl/article/details/49667533) ## 關於 @NotFound * 預設為 EXCEPTION * 若設為 NotFoundAction.IGNORE 會無視 FetchType。也就是無論設定為 FetchType.LAZY 或 FetchType.EAGER,都會以 FetchType.EAGER 加載。 參考資料: [Enum NotFoundAction](https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/annotations/NotFoundAction.html) [2.7.5. @NotFound](https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#associations-not-found) ## 關於 @JoinColumn(nullable=true) 和@ManyToOne(optional=false) @ManyToOne 的 FetchType 預設是 FetchType.LAZY。 ### optional 定義該關聯表(子表)是否必須存在,預設是true。 - false - 主表與子表都必須存在,若子表不存在,查詢結果為null。 - 查詢關係為 **inner join** - true - 子表可以不存在,查詢結果仍會傳回主表,並且屬性值為null。 - 查詢關係為 **left join** ### nullable (待新增說明) 參考資料: [Annotation Type ManyToOne](https://javadoc.io/static/javax.persistence/javax.persistence-api/2.2/javax/persistence/ManyToOne.html#optional--) [Annotation Type JoinColumn](https://javadoc.io/static/javax.persistence/javax.persistence-api/2.2/javax/persistence/JoinColumn.html) [jpa使用manyToOne(opntional=true)踩过的坑及解决](https://www.finclip.com/news/f/38507.html)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up