初始化JPA实体getter中的字段是一种好习惯吗? [英] Is it good practice to initialize fields inside a JPA entity getter?

查看:82
本文介绍了初始化JPA实体getter中的字段是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在POJO Java bean中,这样的代码可能是有益的,特别是对于集合:

In POJO Java beans such code can be beneficial, especially with collections:

class POJO {
    private Collection<X> col;

    public Collection<X> getCol() {
        if (col == null)
           col = new SomeCollection<X>();

        return col;
    }
}

使用<$ c $的代码成为可能c> POJO 调用 pojo.getCol()。isEmpty(),无需额外的空检查,从而使代码更清晰。

It makes possible for the code using POJO to call pojo.getCol().isEmpty() without an additional null check, thus making the code clearer.

假设 POJO 类是JPA实体,这样做是否仍然安全?通过将集合从null初始化为空的集合,持久性数据将不会被更改,但是,我们仍在修改对象,因此持久性提供程序可能会在刷新持久性上下文时产生一些副作用。我们有什么风险?可移植性可能?

Suppose the POJO class is a JPA entity, is it still safe to do that? By initializing the collection from null to an empty one the persistent data won't be changed, but still, we are modifying the object and thus the persistence provider may run some side effects upon flushing the persistence context. What do we risk? Portability maybe?

推荐答案

我强烈建议不要对ORM实体中的属性进行延迟初始化。

I would strongly discourage lazy initialization for properties in an ORM entity.

使用Hibernate对实体属性进行延迟初始化时遇到了严重的问题,所以我强烈反对它。我们看到的问题表现在我们发出搜索请求时发生的保存。这是因为当加载对象时属性为null,但是当调用getter时它将返回惰性初始化对象,因此hibernate(正确地)认为该对象是脏的并且在发出搜索之前将其保存。

We had a serious issue when doing lazy initialization of an entity property using Hibernate, so I would strongly discourage it. The problem we saw was manifest by a save taking place when we were issuing a search request. This is because when the object was loaded the property was null, but when the getter was called it would return the lazy initialized object so hibernate (rightly) considered the object dirty and would save it before issuing the search.

这篇关于初始化JPA实体getter中的字段是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆