How to look for one "default object" from a collection in EJB3 / JPA

I have a Person object with multiple phone numbers.

 @OneToMany(mappedBy="person", cascade=CascadeType.ALL)
 public Set<PhoneNumberOfPerson> getPhoneNumbers() {
    return phoneNumbers;
 }

Now I would like to apply the "get default phone number" method for a person who is looking animated. 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 the default phone number listed on the page with a list of "all" persons in db.

As a beginner JPA, I first 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, led to a very very slow listing page.

, , ? Hibernate .

0
1

PhoneNumbers, , , JOIN FETCH , Person (s).

select p from Person p JOIN FETCH p.phoneNumbers as ph where ph.default = true

PhoneNumber , LEFT JOIN.

0

Source: https://habr.com/ru/post/1764682/


All Articles