Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use subquery into "from" clause in hibernate?

I have three tables: class, student, and teacher

table class
{
    class_id(PK)
}

table student
{
    student_id(PK)
    class_id(PK+FK)
}

table teacher
{
    teacher_id(PK)
    class_id(PK+FK)
}

I have a query in SQL, which works fine.

SELECT data.class_id, count(data.class_id) AS count
FROM ((SELECT class_id FROM student)
        union all
        (SELECT class_id FROM teacher)) AS data
GROUP BY data.user_id
ORDER BY count desc

The query contains sub query in the from clause and union operation. I unable to convert it to the HQL.

please give me the efficient HQL query from the above SQL query.

like image 666
user2000 Avatar asked Jan 03 '13 13:01

user2000


People also ask

Can subquery be used in FROM clause?

Sub queries in the from clause are supported by most of the SQL implementations. The correlation variables from the relations in from clause cannot be used in the sub-queries in the from clause.

Can subquery retrieve data from inner query used in WHERE clause?

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

How do you write a subquery in HQL?

A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed. Note that HQL subqueries can occur only in the select or where clauses.

How do you write a subquery in criteriaBuilder?

where(criteriaBuilder.in(path). value(subquery)); TypedQuery<Object> typedQuery = entityManager. createQuery(select); List<Object> resultList = typedQuery. getResultList();


2 Answers

Unfortunately HQL does not support UNION queries. Two alternative strategies to solve your problem are:

  • Mapping a Pojo to a a view
  • Or Inheritance mapping. Particularly Table per concrete class strategy with an abstract Person superclass inherited both by Student and Teacher seems to fit your problem well:

    select p.id, count(c)
    from Person p join p.classes c
    group by p.id
    order by count(c) desc
    
like image 86
Anthony Accioly Avatar answered Oct 04 '22 18:10

Anthony Accioly


You cannot place a subquery at the from clause in HQL. Only select or where clauses.

like image 35
Roman C Avatar answered Oct 04 '22 17:10

Roman C