Getting related object's ID without fetching it from the database (Play framework)

StackOverflow https://stackoverflow.com/questions/3642130

  •  30-09-2019
  •  | 
  •  

문제

Say I have these two models:

public class City extends Model
{
    @ManyToOne
    private Country country;
}

public class Country extends Model
{
}

I have a City object and want to know the related Country's ID. I could fetch from the database by doing city.getCountry().getId() but that seems very wasteful. How can I just get the ID (stored in the database table as country_id)?

도움이 되었습니까?

해결책

I think fetchType=LAZY is what you need. It creates a proxy-object for the country and it should not do any queries by requesting the id.

@OneToOne(fetch = FetchType.LAZY)
private Country country;

But you also need do mark your id-getter in Country.

public class Country extends Model
{
    @Id
    public Long getId()
    {
        return id;
    }
}

If you don't want do change your id-annotations you can also use this workaround:

  Serializable id = ((HibernateProxy) country).getHibernateLazyInitializer().getIdentifier()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top