使用构造函数初始化 JPA 中的属性
我对使用 JPA 时使用构造函数来初始化列表和其他字段有疑问,具体来说我的问题如下:
假设我有一个实体 bean,它有很多 @OneToMany 关系,我想使用构造函数来初始化它们,这样我就不必在我的控制器中使用这样的语句:
myEntity=new MyEntity();
myEntity.innerList=new ArrayList<Type>();
myEntity.innerList.add(newObject);
所以我会:
public MyEntity(){
innerList=new ArrayList<Type>();
}
现在,问题是......在从数据库映射属性时,JPA 会调用这个构造函数吗?我的意思是,如果我在整个列表之前坚持下来,构造函数会运行并重新初始化我的实体列表吗?多谢。
I have a doubt about using the constructor to initialize lists and other fields when using JPA, specifically my question is as follows:
Suppose I have an entity bean, that has lots of @OneToMany relationships, I would like to use the constructor to initialize them, so that I don't have to use statements like this in my controllers:
myEntity=new MyEntity();
myEntity.innerList=new ArrayList<Type>();
myEntity.innerList.add(newObject);
so instead I would have:
public MyEntity(){
innerList=new ArrayList<Type>();
}
Now, the question is... will JPA call this constructor when mapping properties from the database?. I mean If I had persisted before an entire list, will the constructor run and reinitialize my entites lists?. Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,JPA 将调用实体的无参数构造函数。之后,您的列表将被 JPA 引擎的特定 List 实现替换。这些列表允许延迟加载和 JPA 引擎所需的其他功能。
在这种情况下,我不会太关心不必要的 ArrayList 实例化。这不是典型的 JPA 应用程序花费最多时间的地方。我发现拥有明确的不变量并尊重它们更为重要。这些不变量之一是:我的实体始终具有其他实体的非空列表。
Yes, JPA will call the no-arg constructor of your entity. After that, your lists will be replaced by specific List implementations of your JPA engine. These lists allow lazy-loading and other functionalities needed by the JPA engine.
I wouldn't care much about the needless
ArrayList
instantiation in this case. This is not where a typical JPA application will take the most time. I find it much more important to have clear invariants and to respect them. One of these invariants is : my entity always has a non-null list of other entities.如果我没记错的话,至少在 Hibernate 中,当您
load()
一个实例时,首先会调用无参构造函数,然后分配关联。事实上,当 JPA 分配持久化集合/实体时,在构造函数中创建的那些实例将被丢弃。因此,如果这是您所要求的,那么在构造函数上使用这些初始化是安全的。
If I remember correctly, at least in Hibernate, when you
load()
an instance, in first place the no-argument constructor gets called, and afterwards, associations are assigned. As a matter of fact, those instances created within the constructor will be thrown away when JPA assigns the persisted collection/entities.So, if this is what you are asking, it is safe to use these initializations on the constructor.
是的,JPA 将调用您的无参构造函数(创建一个空的 ArrayList),然后将
innerList
设置为数据库中的值(通过访问字段或调用 setter,具体取决于您的配置)。Yes, JPA will call your no-argument constructor (creating an empty ArrayList) and will then set
innerList
to the values from the databases (by accessing the field or calling the setter, depending on your configuration).