views:

373

answers:

1

I have a Person entity with multiple phone numbers.

 @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?

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:

@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.

A: 

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).

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.

Damo