Criteria api select all fields of related entity

Viewed 111

I am making hibernate criteria query which looks like this:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Profile> query = cb.createQuery(Profile.class);
Root<Profile> profile = query.from(Profile.class);
query.multiselect(
                profile.get("id"),
                profile.get("firstName"),
                profile.get("lastName"),
                profile.get("about"),
                profile.get("birthDate"),
                profile.get("country")
        ).where(cb.equal(profile.get("id"), id));
TypedQuery<Profile> q = em.createQuery(query);
return q.getSingleResult();

And relation is: Profile.java

@ManyToOne
@JoinColumn(name = "country_id", foreignKey = @ForeignKey(
        foreignKeyDefinition = "foreign key (country_id) references country on delete set null"
))
private Country country;

Country.java

@OneToMany(mappedBy = "country")
@JsonIgnore
private Set<Profile> profiles;

The criteria query above will generate 2 queries, 1 - will fetch profile and country id with join, and 2 - will fetch other fields of country. The problem is how do I write my multiselect criteria query with all fields of the related country? if I just use default jpa findById, it is generating query which is selecting all of the related country fields and then join, and my criteria query selects country id, joins, and then selects other fields in another query. I tried to change profile.get("country") to profile.join("country") and making Root<Country> country = query.from(Country.class) and then selecting variable country rather than profile.get("country"), but nothing of this helped

0 Answers
Related