如何热切地获取单个“默认"邮件. EJB3/JPA中的集合中的实体 [英] How to eagerly fetch a single "default" entity from a collection in EJB3/JPA

查看:105
本文介绍了如何热切地获取单个“默认"邮件. EJB3/JPA中的集合中的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个电话号码的Person实体.

I have a Person entity with multiple phone numbers.

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

现在,我想为渴望获取的Person实现一个获取默认电话号码"方法.此默认电话号码是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.

作为JPA初学者,我最初使用以下方法进行了尝试:

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.

那么,有什么方法可以定义一个瞬态属性,该瞬态属性基于某个查询从一组实体中获取单个实体?我正在使用Hibernate作为持久性提供程序.

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.

推荐答案

您最好的选择可能是在PhoneNumbers表上具有一个字段,以表明它是默认号码,然后对返回该值的查询执行JOIN FETCH人.

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

如果可能没有某个人的电话号码,请使用LEFT JOIN.

If there is the possibility of there being no PhoneNumber for a Person then use a LEFT JOIN.

这篇关于如何热切地获取单个“默认"邮件. EJB3/JPA中的集合中的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆