I have a Person entity with multiple phone numbers.
我有一个包含多个电话号码的Person实体。
@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
public Set<PhoneNumberOfPerson> getPhoneNumbers() {
return phoneNumbers;
}
Now I would like to implement a "get default phone number" method for Person that is eagerly fetched. This default phone number is one of the phone numbers in the phoneNumbers set. Is there any way to do this?
现在我想为急切获取的Person实现一个“获取默认电话号码”方法。此默认电话号码是phoneNumbers设置中的电话号码之一。有没有办法做到这一点?
The reason I'm trying to implement this is to have this default phone number listed on a page that lists "all" of the persons in the db.
我试图实现这一点的原因是在列出数据库中“所有”人员的页面上列出此默认电话号码。
As a JPA beginner I initially tried it with the following method:
作为JPA初学者,我最初尝试使用以下方法:
@Transient
public PhoneNumberOfPerson getDefaultPhoneNumber(){
if(this.getPhoneNumbers().size()==0)
return null;
return this.getPhoneNumbers().iterator().next();
}
But this of course resulted in a very very slow listing page.
但这当然导致了一个非常慢的列表页面。
So is there any way to define a transient property that gets a single entity from a collection of entities based on some query? I'm using Hibernate as my persistence provider.
那么有没有办法定义一个瞬态属性,它根据某些查询从一组实体中获取单个实体?我正在使用Hibernate作为我的持久性提供程序。
1 个解决方案
#1
0
Your best bet is probably to have a field on the PhoneNumbers table to indicate that it is the default number and then do a JOIN FETCH on the query that returns the Person(s).
你最好的选择可能是在PhoneNumbers表上有一个字段,表明它是默认的数字,然后在返回Person的查询上做一个JOIN FETCH。
select p from Person p JOIN FETCH p.phoneNumbers as ph where ph.default = true
If there is the possibility of there being no PhoneNumber for a Person then use a LEFT JOIN.
如果有人可能没有PhoneNumber,那么使用LEFT JOIN。
#1
0
Your best bet is probably to have a field on the PhoneNumbers table to indicate that it is the default number and then do a JOIN FETCH on the query that returns the Person(s).
你最好的选择可能是在PhoneNumbers表上有一个字段,表明它是默认的数字,然后在返回Person的查询上做一个JOIN FETCH。
select p from Person p JOIN FETCH p.phoneNumbers as ph where ph.default = true
If there is the possibility of there being no PhoneNumber for a Person then use a LEFT JOIN.
如果有人可能没有PhoneNumber,那么使用LEFT JOIN。