Search code examples
javapostgresqlhibernatehibernate-criteriacriteria-api

Hibernate - How to select just the foreign key value using Criteria Query without doing a Join?


So there is this similar (almost identical) question: How to select just the foreign key value using Criteria Query? but I need to avoid doing the join.

So I have two tables, one with a FK to the other

(Service)

  • id
  • name
  • account_id

(Account)

  • id
  • name

Service class has the FK defined this way:

@Entity
public class Service extends BaseDbEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Account account;

...

and what I want to do is query all the Service's that correspond to a given account, having the accountId, without doing a JOIN, because the id is already in the Service table.

Now, my criteria query looks like this:

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Service> criteria = cb.createQuery(Service.class);
Root<Service> root = criteria.from(Service.class);
criteria
        .select(root)
        .where(cb.equal(root.join("account").get("id"), accountId));
session.createQuery(criteria).getResultStream();

This ends up generating this query:

Hibernate: select service0_.id as id1_3_, service0_.name as name4_3_, service0_.account_id as account_id6_3_ from Service service0_ inner join Account account1_ on service0_.account_id=account1_.id where account1_.id=?

Which doesn't make sense.. it does a join on a field and then just creates a where clause for that field.

If I do:

root.get("account_id")

it just throws an exception saying the field is not available.

What is the correct way to avoid this?


Solution

  • Ok I just found the answer to my question:

    Instead of doing

    root.join("account").get("id")
    

    I just needed to do:

    root.get("account").get("id")
    

    which avoids performing the JOIN.