Can I add amounts from multiple tables in hql - java

I would like to perform a query in HQL similar to this in SQL:
SELECT (
SELECT COUNT(*) FROM EMPLOYER +
SELECT COUNT(*) FROM COMPANIES
)
FROM DUAL
When I add "FROM DUAL" to the query I get an error:
org.hibernate.hql.ast.QuerySyntaxException: DUAL is not mapped
And if I leave off the "FROM DUAL" I get:
org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree
Any recommendations?

In SQL, subqueries need their own set of parentheses, so try this:
SELECT ((SELECT COUNT(*) FROM EMPLOYER) +
(SELECT COUNT(*) FROM COMPANIES)
)
If that doesn't work, resort to a from clause:
SELECT e.cnt + c.cnt
FROM (SELECT COUNT(*) as cnt FROM EMPLOYER
) e CROSS JOIN +
(SELECT COUNT(*) as cnt
FROM COMPANIES
) c

Since you didn't join the Company and Employee tables you'd better run two queries:
int companyCount = ((Number) getSession().createQuery("select count(*) from Company").uniqueResult()).intValue();
int employeeCount = ((Number) getSession().createQuery("select count(*) from Employee").uniqueResult()).intValue();
int totalCount = companyCount + employeeCount;
The (Number) is needed since PostgreSQL returns a BigInteger while HDSQLDB returns an Integer, but both are subclasses of Number.

Related

How to execute joins of an entity with the result of a query in Hibernate

I want to run the following SQL in hibernate:
SELECT c.id, c.name, ipc.total
FROM Category c,
(
SELECT comm.category.id as id, count(*) as total
FROM Commerce as comm
GROUP BY comm.category.id
) ipc
WHERE c.id = ipc.id
This is my attempt to write that one in JQL but I get an error. It doesn't seem to like my join against a query result.
Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 86 [SELECT c.id, c.name, ipc.total FROM com.brujulasolutions.directorio.model.Category c,( SELECT comm.category.id as id, count(*) as total FROM com.brujulasolutions.directorio.model.Commerce as comm GROUP BY comm.category.id ) ipc WHERE c.id = ipc.id]
SELECT c.id, c.name, ipc.total
FROM Category c,
(
SELECT comm.category.id as id, count(*) as total
FROM Commerce as comm
GROUP BY comm.category.id
) ipc
WHERE c.id = ipc.id
Hibernate query language does not directly support this type of update join. Instead, we can use a correlated subquery in the select clause:
SELECT c.id, c.name,
(SELECT COUNT(*)
FROM Commerce AS comm
WHERE comm.category.id = c.id) AS total
FROM Category c

JPA select from select distinct

I'm trying to execute the following SQL query writing native query in JPA:
SELECT id FROM (
SELECT DISTINCT id, DENSE_RANK() OVER (ORDER BY id) AS row FROM table
) WHERE row BETWEEN 1 AND 10;
In the Query annotation I wrote:
#Query(value = "SELECT t.id FROM (SELECT DISTINCT(e.id), DENSE_RANK() OVER (ORDER BY e.id) AS row FROM Table e) t WHERE row BETWEEN ? AND ?")
but I have syntax errors here FROM (SELECT.
Please, can you help me?
You have probably forgot nativeQuery=true
Try this:
#Query(value = "SELECT t.id FROM (SELECT DISTINCT(e.id), DENSE_RANK() OVER (ORDER BY e.id) AS row FROM Table e) t WHERE row BETWEEN ? AND ?", nativeQuery = true)

Subquery with Inner Join in HQL

I want to print title from Movies table which has Foreign key Movie_id in Rating table.In rating table we have to get top 10 results based on movie_id occurrence .Since Limit is not allowed in HQL so setMaxResults is used
Query q=session.createQuery("select Title from Movies as M Inner Join ( SELECT Movie_id, COUNT(*) FROM Rating GROUP BY Movie_id ORDER BY COUNT(*) DESC LIMIT 10 ) as R ON M.Movie_id=R.Movie_id").setMaxResults(10);
Exception is:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 59 [select Title from com.rahul.model.Movies as M Inner Join ( SELECT Movie_id, COUNT(*) FROM com.rahul.model.Rating GROUP BY Movie_id ORDER BY COUNT(*) DESC LIMIT 10 ) as R ON M.Movie_id=R.Movie_id]
Since HQL doesn't support subquery how to achieve it ?
You can write this query as a JOIN/GROUP BY:
select m.Title
from Movies m Inner Join
Rating r
on m.Movie_id = r.Movie_id
group by m.Movie_Id, m.Title
order by count(*) desc
limit 10;
Resolved
Query q=session.createQuery("select m.title from Movies m Inner Join Rating r on m.movie_id = r.movie_id group by m.movie_id, m.title order by count(*) desc").setMaxResults(10);

Using a Query, Joining 4 tables in Hibernate Mapping

Currently i'm using PostgreSQL database in my Spring MVC web application. I'm able to get the values when i execute the query in PgAdmin tool.
In my query, I'm trying to join 4 tables and get the values.
My query is:
SELECT (s.school_id, u.first_name, u.last_name, u.username, u.email, p.plan_name, s.start_date, s.end_date, s.subscription_price, (SELECT COUNT(*) FROM school_user t WHERE t.user_type = 'T' and t.school_id = s.school_id), (SELECT COUNT(*) FROM school_user t WHERE t.user_type = 'A' and t.school_id = s.school_id), (SELECT COUNT(*) FROM school_user t WHERE t.user_type = 'S' and t.school_id = s.school_id)) FROM school s inner join user u on s.user_created = u.user_id inner join plan p on s.current_plan = p.plan_Id where s.application_id = 30 and s.site_id = 42;
When I use this same query in my Dao method, I'm getting error like:
No Dialect mapping for JDBC type: 1111
Code used in dao method:
public List<Object[]> getInformationValues(int applicationId, int siteId) throws HibernateException {
Session session = getCurrentSession();
Query query = session.createSQLQuery("SELECT (s.school_id, u.first_name, u.last_name, u.username, u.email, p.plan_name, s.start_date, s.end_date, s.subscription_price, (SELECT COUNT(*) FROM school_user t WHERE t.user_type = 'T' and t.school_id = s.school_id), (SELECT COUNT(*) FROM school_user t WHERE t.user_type = 'A' and t.school_id = s.school_id), (SELECT COUNT(*) FROM school_user t WHERE t.user_type = 'S' and t.school_id = s.school_id)) FROM school s inner join user u on (s.user_created = u.user_id) inner join plan p on (s.current_plan = p.plan_Id) where s.application_id = :applicationId and s.site_id = :siteId") .setParameter("applicationId", applicationId) .setParameter("siteId", siteId);
List<Object[]> results = query.list();
return results;
}
Is there any way to fix this issue?

Convert Postgres Query to JPQL

How to convert below PostreSQL query into JPQL? I mainly stuck with row_number(), partition and when case.
select p, c from product p left join
(
select
c.product_id, c.id, c.status, c.start_date,
row_number() over (partition by product_id order by (case status when 'EXPIRED' then 2 else 1 end) asc, start_date desc) as row_number
from contract c
order by product_id
) c
on
p.id = c.product_id and c.row_number = 1
order by p.id, c.start_date;

Categories