场景: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")
这样即使找不到相应的记录也不会报错。
网友评论