Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Criteria api join after fetch throws Invalid path error

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

like image 829
romanvintonyak Avatar asked Nov 24 '25 12:11

romanvintonyak


1 Answers

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");
like image 187
Shengfeng Li Avatar answered Nov 27 '25 10:11

Shengfeng Li