3

I have three simple entities:

@Entity
public class Category {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany(fetch = FetchType.LAZY)
    private List<Subject> subjects;
}

@Entity
public class Subject {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany(fetch = FetchType.LAZY)
    private List<Topic> topics;
}


@Entity
public class Topic {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
}

and I use criteria api to obtain the data. I need subjects to be pre-fetched.

CriteriaBuilder cb = this.em.getCriteriaBuilder();
CriteriaQuery<Category> cq = cb.createQuery(Category.class);
Root<Category> root = cq.from(Category.class);
cq.select(root);
Join subjects = (Join) root.fetch("subjects");
Join topics = subjects.join("topics");
Predicate predicate1 = cb.equal(topics.get("name"), "topic2");
cq.where(predicate1);

List<Category> resultList = this.em.createQuery(cq).getResultList();

But I get the following exception:

org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'generatedAlias2.name' [select generatedAlias0 from entities.Category as generatedAlias0 inner join fetch generatedAlias0.subjects as generatedAlias1 where generatedAlias2.name=:param0]

Can anybody tell me what it is the problem. By the way, the error won't appear if I use join instead of fetch

2 Answers 2

2

I met exactly the same problem with you. Through the sql query, the last join statement was missing. As your exception told you, the generatedAlias2 was never been aliased at all before using it.

And my solution is simple and it works. Convert fetch to Join at the very least.

Here is an example

Fetch subjects = root.fetch("subjects");
Join topics = (Join) subjects.fetch("topics");
Predicate predicate1 = cb.equal(topics.get("name"), "topic2");
Sign up to request clarification or add additional context in comments.

Comments

0

The solution works. But it will fetch all data of Topic, too.

The same query in JPQL would looks like this one:

Select c from Category c
join fetch c.subjects s
join s.topics t 
where t.name = 'topic2'

And it will work without any problem. So why the CriteriaQuery behaves different?

2 Comments

I don't know why. It seems to be a bug.
I have faced the same issue in my code, any idea if a newer version solves this issue? I am running spring boot 2.2.4.RELEASE with Hibernate core 5.4.10.Final

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.