SELECT a.id,COUNT(entity2.number)
AS "numbers" ,SUM(CASE WHEN entity2.status= 'A' THEN 1 ELSE 0 END)
AS "blocked" FROM entity1 a
LEFT OUTER JOIN entity ON a.id = entity2.id
WHERE a.id LIKE 'ZX13%'
GROUP BY a.id.
i am using criteria builder api to perform above operation.
If i use criteriaQuery.multiselect(listSelections).groupBy(a.id) it works fine but when i use criteriaQuery.multiselect(listSelections).distinct(true).groupBy(a.id) it is not working fine. I want distinct results too.
Why it is not working as expected?
How to resolve this?
Related
I have a JPQL subquery in which I want to return a list of customerIds that meet a specific condition based on a ManyToOne relationship as shown below:
SELECT c.customerId
FROM Customer c
INNER JOIN FETCH c.customersChild cc
LEFT JOIN FETCH c.childsPet cp on cp.name = 'Rover'
GROUP BY c.customerId
HAVING (COUNT(cp.name) / COUNT(*)) = 1
In this case, the customer should only be present in the list if all of their childrens' pet's names are Rover. The HAVING (COUNT(cp.name) / COUNT(*)) = 1 clause works as-is in Oracle (SQL), since COUNT(cp.name) counts the number of non-null rows for each customer, and COUNT(*) counts the total number of rows (including nulls present due to the left join) for each customer... I believe COUNT(cp.name) works in JPQL but it doesn't seem like there is equivalent for COUNT(*)... does anyone know if there is a way to count all the rows within a group including nulls?
I would suggest you rewrite your query to the more understandable anti-join variant:
SELECT c.customerId
FROM Customer c
WHERE NOT EXISTS (
SELECT 1
FROM c.customersChild cc
JOIN cc.childsPet cp
WHERE cp.name = 'Rover'
)
I am a Hibernate newbie and i have this below query. It is working as i expected. These two tables are not associated. Is there a way to get the same result by using Criteria API or how can i run this query via Hibernate ? Any help would be appreciated.
SELECT p.title, c.content
FROM posts p
LEFT JOIN comments c ON p.id = c.post_id
WHERE p.status = 'A' AND (p.title iLIKE '%r%' OR c.content iLIKE '%r%');
Criteria API needs a path between entities, so I'm not sure this join could be done using Criteria API. Better do it with HQL if you have Hibernate >= 5.1:
select p.title, c.content
from org.example.Posts p
left outer join org.example.Comments c
on p.id = c.id
where p.status = 'A' AND (lower(p.title) LIKE '%r%' OR lower(c.content) LIKE '%r%');
Still, you could stick to using SQL queries with Hibernate or better still, create association between Posts and Comments.
derived from this question, is it possible to use HQL or Criteria for the following SQL statement:
SELECT
e.type,
count(e),
count(d),
count (case when gender = 'male' then 1 else NULL end) AS NumberOfMaleEmployees
from Department d
JOIN d.employees e
WHERE e.dead = 'maybe'
GROUP BY e.type
Although google comes up with a few hits that state HQL supports CASE statements, Hibernate 3.6.6 fails with a
QuerySyntaxException: unexpected token: CASE
when I create the query above on an EntityManager instance.
How much of a bad idea is it, to create another query for every e.type to determine the number of males manually, e.g. for every e.type
SELECT
count(e),
from Department d
JOIN d.employees e
WHERE e.dead = 'maybe', e.type = ugly
Since there could be quite a few types, this is potentially slow. I'd like the database to do the work for me.
Well, it seems, case statements are supported:
http://docs.jboss.org/hibernate/core/3.5/reference/en/html/queryhql.html
They just don't seem to work within count(). An alternative would be using sum(case when... then 1 else 0 end) instead
This one is odd...
I have an hql query that ignore the GOUP BY if ORDER BY is included.
it will perform the query without the group by,
but if I remove the order by it will work fine
list = getSession().createQuery(
"SELECT
Brand.name as Brand_name
, Brand.url as Brand_url
, Brand.email as Brand_email
, Brand.brandId as Brand_brandId
, Brand.description as Brand_description
FROM com.affiliates.hibernate.Brand Brand
INNER JOIN Brand.users as users
WHERE 1=1
AND users.userId>'0'
order by Brand.email ASC
group by brandId"//this one will be ignored because of the order by
).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
sql generated:
select
brand0_.NAME as col_0_0_,
brand0_.URL as col_1_0_,
brand0_.EMAIL as col_2_0_,
brand0_.DESCRIPTION as col_3_0_
from
BRAND brand0_
inner join
USERS_BRANDS users1_
on brand0_.BRAND_ID=users1_.BRAND_ID
inner join
USER user2_
on users1_.USER_ID=user2_.USER_ID
where
1=1
and user2_.USER_ID>'0'
order by
brand0_.EMAIL ASC limit ?
First, notice that BRAND.BRAND_ID has been drop from the column projections in the SQL. This is probably related to the group by being dropped as well.
Second, notice there are no aggregate functions defined in the query. Group only works on aggregations. Try adding an aggregate function, such as max, to all of the columns. This might be the cause of the problem
Last, try fully qualifying brandId in the HQL to eliminate any confusion:
group by Brand.brandId
You should apply orderby after groupby but you have written as
order by Brand.email ASC
group by brandId"//this one will be ignored because of the order by
).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
But Change to:
group by brandId"//this one will be ignored because of the order by
).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
order by Brand.email ASC
Then it will work
I'm trying to translate a SQL quest into Hibernate criteria.
My quest is working in SQL :
select * from objective
left outer join conditionstate
on objective.conditionid = conditionstate.conditionid
and conditionstate.personid = XXXX
where objective.toto_id = YYYYY
The objective is not directly mapped to the condition_state, but into a condition.
objective --> condition <-- condition_state
I've tested something like :
final DetachedCriteria criteriaObjective =
DetachedCriteria.forClass(Objective.class);
criteriaObjective.createAlias("conditionState", "conditionState", Criteria.LEFT_JOIN);
without success..
It's hard to suggest something without seeing your actual mappings. Going by your explanation and assuming that both condition and conditionState are mapped as many-to-one, you'd write something like:
final DetachedCriteria criteriaObjective =
DetachedCriteria.forClass(Objective.class);
criteriaObjective
.createCriteria("condition", Criteria.LEFT_JOIN)
.createCriteria("conditionState", Criteria.LEFT_JOIN)
.add(Restrictions.eq("personid", "XXXX") );
criteriaObjective.add(Restrictions.eqProperty("toto_id", "YYYY") );
Note that the above is NOT equivalent to the SQL query you've provided because "personid" condition will be generated as part of "WHERE" clause. As far as I know it's impossible to do a left join with condition using Criteria API - you may need to use HQL instead which provides with keyword for that exact purpose:
select o from objective as o
left join o.condition as c
left join c.conditionState as cs
with cs.person_id = 'XXXX'
and o.toto_id = 'YYYY'