【问题标题】:Getting related object's ID without fetching it from the database (Play framework)获取相关对象的 ID 而不从数据库中获取它(Play 框架)
【发布时间】:2010-09-04 11:53:34
【问题描述】:
假设我有这两个模型:
public class City extends Model
{
@ManyToOne
private Country country;
}
public class Country extends Model
{
}
我有一个 City 对象并想知道相关 Country 的 ID。我可以通过 city.getCountry().getId() 从数据库中获取,但这似乎非常浪费。我怎样才能得到ID(存储在数据库表中country_id)?
【问题讨论】:
标签:
hibernate
playframework
【解决方案1】:
我认为 fetchType=LAZY 是您所需要的。它为国家创建了一个代理对象,它不应该通过请求 id 来进行任何查询。
@OneToOne(fetch = FetchType.LAZY)
private Country country;
但您还需要在 Country 中标记您的 id-getter。
public class Country extends Model
{
@Id
public Long getId()
{
return id;
}
}
如果您不想更改您的 id-annotations,您也可以使用此解决方法:
Serializable id = ((HibernateProxy) country).getHibernateLazyInitializer().getIdentifier()