manyToOne出现EntityNotFoundException



场景:Account与User的关系是manyToOne的关系,一个用户可能有多个账号,如果账号表中记录的用户id为5,但在用户表中没有id为5的记录。这是非常规情况,一般在删除用户的时候也应该删除Account与User的关联关系。但是为了展示Account列表,即使id对应的User不存在也应该展示Account的信息,而不是失败报错。

返回的错误形式:

javax.persistence.EntityNotFoundException: Unable to find com.indianretailshop.domain.User with id 5 
at org.hibernate.ejb.Ejb3Configuration$Ejb3EntityNotFoundDelegate.handleEntityNotFound(Ejb3Configuration.java:137) 
at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:189) 
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:178) 
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)

办法就是添加注解:

@ManyToOne(targetEntity=User.class)
@NotFound(action=NotFoundAction.IGNORE)
@JoinColumn(name="user_id")

这样即使找不到相应的记录也不会报错。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容