JPA - 注入或实例化自定义属性/对象以进行 JSF 写访问?
我正在使用 OpenJPA,想知道如何引用另一个自定义实体。假设有一个人和一个地址。两者都是我的建模实体。
Person 如何正确引用地址?
这样:
@Entity
public class Person {
@Column
@Inject
Address adr;
}
或者像这样:
@Entity
public class Person {
@Column
Address adr = new Address();
}
我宁愿注入或实例化的原因是当我访问这样的地址时看到空指针异常:#{myBean.personA.adr.street}
因为当对象不是从现有记录加载而是在创建新记录时使用时,adr 返回 null
您如何解决实体中的这些问题?我错过了什么吗?顺便说一句:我使用 openJPA 和 Webbeans
I am using OpenJPA and was wondering how to reference another custom entity. Let's assume there is a Person and an Address. Both are my modeled entities.
How would Person correctly refer to Address?
This way:
@Entity
public class Person {
@Column
@Inject
Address adr;
}
or like this:
@Entity
public class Person {
@Column
Address adr = new Address();
}
The reason why I rather want to inject or instantiate is I see null pointer exception when I access Address like this: #{myBean.personA.adr.street}
because adr returns null when the object is not loaded from an existing record, but used when creating a new one
How do you solve auch issues in your entities? Am I missing sth.? BTW: I use openJPA and Webbeans
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会在您显式创建新的
Person
时创建它。或者,也可以在
Person
中完成这项工作,这样您就不需要重复它:
I would create it at the point where you're explicitly creating a new
Person
.Or, alternatively, do the job in
Person
so that you don't need to repeat it:with
您可以尝试定义构造函数来初始化变量的默认值。这样,每当创建对象时,它都会先运行构造函数,然后再应用数据库中的任何值。假设您的地址对象在数据库中没有空值,则此方法有效。
一般来说,尽管您希望在引用那么深的对象遍历之前使用空检查,因为如果您尚未验证数据条目和/或表没有非空约束,则数据可能具有空值。
You could try defining a constructor to initialize default values for your variables. This way any time your object is created it would run the constructor first before applying any values form the database. This works assuming your address object does not have a null value in the database.
Generally though you want to use null checks before referencing an object traversal that deep since your data could potentially have null values if you aren't already validating data entry and/or the tables don't have not null constraints.
我不建议直接从 JSF 页面引用您的实体。您可以首先将表单数据保存到一些中间对象中,然后调用一些 EJB 服务,该服务将从临时对象中初始化实体并保留它。
I wouldn't recommend referencing your entities from JSF pages directly. You could save your forms data into some intermediary objects first, and then call some EJB service which would initialize entity from your temporary object and persist it.