【问题标题】:Can I detect hibernate not found annotation work我可以检测到休眠未找到注释工作吗
【发布时间】:2015-08-31 10:46:51
【问题描述】:

我有两个具有多对一关系的对象:

对象 1:

@Entity
@Table(name=”Person”)
public class Person {
    Long id;
    String name;
    String surname;
    … // other fields

    @NotFound(action=NotFoundAction.IGNORE)
    @ManyToOne @JoinColumn(name = "groupId")
    Group group;

    ....all the getters and setters…
}

对象 2:

public class Group {
    @Id
    @Column
    Long groupId;

    @Column
    protected String groupName;

    @Column(precision = 15, scale = 0)
    protected long exampleFieldId;

    ...rest of code....
}

Person 类中的字段“组”可以为空。如何确定从数据库或“NotFound”注释中获取空值的位置?

这种情况可能是以下情况:数据库级别的用户可以访问一组有限的组。

【问题讨论】:

    标签: spring hibernate annotations many-to-one


    【解决方案1】:

    您可以尝试用下面的getter替换@NotFound并在它捕获ObjectNotFoundException时进行调试,但如果您的组已经为null,我认为hibernate可能会使用null初始化组对象,这可能会导致NPE,但您可以使用此代码进行调试如果您想要一些休眠代理的自定义加载行为,请使用注释 @NotFound。

    @ManyToOne @JoinColumn(name = "groupId")
    Group group;
    
    private Group getGroup(){
       if(!Hibernate.isInitialized(group)) {
            try {
                 Hibernate.initialize(group);
            } catch(org.hibernate.ObjectNotFoundException e) {
                group = null;
            }
        }
      return group;
    }
    

    【讨论】:

    • 我有这个错误:org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.test.datamodel.mappings.Group with id 123;嵌套异常是 javax.persistence.EntityNotFoundException: Unable to find com.test.datamodel.mappings.Group with id 123
    • 我尝试按照您的方法进行操作,但即使我使用 Hibernate.isInitialized() 检查对象,它实际上表示 它已初始化,即使它没有找到。因此,我必须以某种方式控制此行为的唯一方法仍然是在我尝试从 null 对象访问某些属性时捕获 NPE 异常,这不是最聪明的方法。但我不知道如何检查对象本身的存在,而不是它的“初始化”。
    【解决方案2】:

    'Not found' 在这种情况下与 null 相同。你不能用 null 初始化组,因为你会得到 NullPointerException。

    【讨论】:

    • 不一定那样。 Person 中的组可以为空。事实上,Group 是一个 View。并且由于某种原因,它可能不包含基表的某些值。当一个人提到一个不存在的群体时,我们就会遇到这种情况。我不仅想用 null 填充 Person 中的字段组,还想向操作员显示他没有访问 Group 的这个值的权限。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2012-04-16
    相关资源
    最近更新 更多