How can I solve this query with Hibernate's detached criteria? The hardest part for me is to bring the and u1.abrechnungsDatum is null into the subselect.
I want a query like this:
select *
from
patient as p
where
p.krankenstand = ?
and
? < ( select count(*) from ueberweisung u1 where p.id = u1.patient_id
and u1.abrechnungsDatum is null)
I have tried it with this
DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient");
dc.add(Restrictions.eq("krankenstand", true));
DetachedCriteria nab = dc.createCriteria("ueberweisungs", "nab");
nab.add(Restrictions.isNull("nab.abrechnungsDatum"));
dc.add(Restrictions.sizeGt("ueberweisungs", 0));
which gives me the following SQL-Statement
select
*
from
patient this_
inner join
ueberweisung nab1_
on this_.id=nab1_.patient_id
where
this_.krankenstand=?
and nab1_.abrechnungsDatum is null
and ? < (
select
count(*)
from
ueberweisung
where
this_.id=patient_id
)
As you can see, the and-clause for the field abrechnungsDatum is not inside the subselect. How can I achieve to get this inside?
Try this instead:
DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient");
dc.add(Restrictions.eq("krankenstand", true));
DetachedCriteria subquery = DetachedCriteria.forClass(Ueberweisung.class);
subquery.add(Restrictions.isNull("abrechnungsDatum"));
dc.add(Subqueries.ltAll(0, subquery));
Related
I try do the folow JPQL clause to criteria Api
SELECT new ProductDTOOut(p.id,p.name,
(SELECT pr.price FROM Price pr WHERE pr.product.id = p.id and pr.company.id = :companyId) )
FROM Product p
without success,
how can I do it ?
tnx advanced
I know solve my problem follow answer :
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<ProductDTOOut> criteriaQuery = cb.createQuery(ProductDTOOut.class);
// create query
Root<Product> rootFrom = criteriaQuery.from(Product.class);
// creating subquery
Subquery<Double> subquery = criteriaQuery.subquery(Double.class);
Root<Price> subqueryRoot = subquery.from(Price.class);
subquery.select(subqueryRoot.get(Price_.PRICE));
subquery.where(
cb.equal(rootFrom.get(Product_.ID),
subqueryRoot.get(Price_.PRODUCT).get(Product_.ID)),
cb.equal(
subqueryRoot.get(Price_.COMPANY).get(Company_.ID), companyId));
criteriaQuery.select(cb.construct(ProductDTOOut.class,
rootFrom.get(Product_.ID),
rootFrom.get(Product_.NAME),
subquery // here put subquery
));
TypedQuery<ProductDTOOut> query = manager.createQuery(criteriaQuery);
return query.getResultList();
I hope that I helped someone with the same question.
When i try to execute the following query in mysql , it works perfectly. But when we try it via Hibernate(3.2) ,hibernate is not differentiating m.NAME and o.NAME. It is returning the same result for both as m.NAME.
SELECT m.NAME, m.SCREENNAME, rm.ADDRESS, o.NAME FROM remoteunit rm LEFT JOIN mo m ON rm.MOID = m.ID JOIN overallcustomfields ocf ON m.ID = ocf.MOID LEFT JOIN organization o ON ocf.ORGID = o.ID WHERE m.DOMAINID = 2
Iam using the following code
Transaction transaction = session.beginTransaction();
SQLQuery query = session.createSQLQuery(queryString);
query.setLong("customId", customId);
remoteUnitList = (ArrayList<Object[]>)query.list();
transaction.commit();
Note: Forced to use SQLQuery in Hibernate since the columns are dynamically populated and more constraints.
Did you try SELECT m.NAME as m_name, o.NAME as o_name.... I faced the same problem and it went of with this change.
I want to create a typed query.
TypedQuery<PubThread> query = em.createQuery(queryString, PubThread.class);
query.setParameter("threadId", threadId);
List<PubThread> otherPubThreads = query.getResultList();
In the queryString is the following SQL (currently without param and static selection values)
SELECT pt2 FROM pubthread pt2
JOIN pub_pubthread ppt2 ON pt2.id = ppt2.pubThreads_id
JOIN pub p2 ON ppt2.pups_id = p2.id
JOIN pubcategory pc2 ON p2.pubCategoryId = pc2.id
WHERE pt2.id != 1 and EXISTS (
SELECT DISTINCT(pt.id)
FROM pubthread pt
JOIN pub_pubthread ppt ON pt.id = ppt.pubThreads_id
JOIN pub p ON ppt.pups_id = p.id
JOIN pubcategory pc ON p.pubCategoryId = pc.id
WHERE pc2.id = pc.id and pt.id = 1
)
It does work, if I limit the String to a simple select: SELECT Distinct(pt2.id), pt2.name FROM pubthread pt2. As soon I add a JOIN line to it, it will complain. How do you properly query with JOINS in JPA? The error is:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column 81 [SELECT pt2 FROM com.brayan.webapp.model.PubThread pt2 JOIN pub_pubthread ppt2 ON pt2.id = ppt2.pubThreads_id ]
Doubtless, a criteria query would be nicer. I accept that as part of the solution space.
When you call createQuery you have to write HQL but not SQL (your queryString is not HQL).
In HQL you have to join objects according to your mapping entities.
If you sill need SQL query use createNativeQuery method.
See documentation about how to create HQL query.
Got it. See below a fully example of joins. It consists of:
multiple joins (join-chaining)
a subquery
a predicate correlation/equation over join tables, other than the root table.
I also commented the obsolete code lines for other to see what a wrong approach.
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery mainQuery = criteriaBuilder
.createQuery(PubThread.class);
// 1) MainQuery
// Create the FROM
Root<PubThread> rootPubThread = mainQuery.from(PubThread.class);
// Create the JOIN from the first select: join-chaining. You only need the return for ordering. e.g. cq.orderBy(cb.asc(categoryJoin.get(Pub_.title)));
Join<Pub, PubCategory> categoryJoin = rootPubThread.join(PubThread_.pups).join(Pub_.pubCategory);
// Create the WHERE
mainQuery.where(criteriaBuilder.not(criteriaBuilder.equal(rootPubThread.get(PubThread_.id), threadId)));
// Create the SELECT, at last
mainQuery.select(rootPubThread).distinct(true);
// 2) Subquery
Subquery<PubThread> subquery = mainQuery.subquery(PubThread.class);
Root<PubThread> rootPubThreadSub = subquery.from(PubThread.class);
//subquery.where(criteriaBuilder.equal(rootPubThread.get(PubThread_.id), threadId));
Join<Pub, PubCategory> categoryJoinSub = rootPubThreadSub.join(PubThread_.pups).join(Pub_.pubCategory);
subquery.select(rootPubThreadSub);
//Predicate correlatePredicate = criteriaBuilder.equal(rootPubThreadSub.get(PubThread_.id), rootPubThread);
Predicate correlatePredicate = criteriaBuilder.and(
//criteriaBuilder.equal(rootPubThreadSub.get(PubThread_.id), rootPubThread),
criteriaBuilder.equal(categoryJoinSub.get(PubCategory_.id), categoryJoin.get(PubCategory_.id)),
criteriaBuilder.equal(rootPubThreadSub.get(PubThread_.id), threadId)
);
subquery.where(correlatePredicate);
//Predicate correlatePredicate = criteriaBuilder.equal(rootPubThreadSub.get(PubThread_.id), rootPubThread);
Predicate mainPredicate = criteriaBuilder.and(
criteriaBuilder.not(criteriaBuilder.equal(rootPubThread.get(PubThread_.id), threadId)),
criteriaBuilder.exists(subquery)
);
//cq.where(criteriaBuilder.exists(subquery));
mainQuery.where(mainPredicate);
I need to do this query with Java + Hibernate.
SELECT
table2.id,
COUNT(table2.id) AS count
FROM
table1
JOIN table2
ON table1.fk_tb2 = table2.id --many2one
GROUP BY
table2.id
I would use DetachedCriteria class.....how can i do this ?
Try using projections like this:
Criteria table1Crit = session.createCriteria("table1");
Criteria table2Crit = table1Crit.createCriteria("table2", Criteria.INNER_JOIN);
table2Crit.setProjection( Property.forName("id").count() );
use your query with createNativeQuery method
I am quite new to JPA and I have encountered a problem with understanding one particular query. I have rewritten in to the CriteriaQuery but the result and the query translated to SQL is not correct.
Background situation: I have a table of store transaction (moves) and the current amount in the store is defined as a sum of all changes. Now I want to select and display the last moves as they also contain an information about the resulting amount on store.
So, this is the query in JPQL:
SELECT m FROM move m WHERE m.id = (
SELECT MAX(o.id) FROM move o WHERE (o.item = m.item AND m.cell.store = :s)
I tried to rewrite it to the following CriteriaQuery:
CriteriaBuilder builder = model.getCriteriaBuilder();
CriteriaQuery<Move> query = builder.createQuery(Move.class);
Root<Move> root = query.from(Move.class);
Subquery<Long> subquery = query.subquery(Long.class);
Root<Move> subroot = subquery.from(Move.class);
subquery.select(builder.max(subroot.get("id").as(Long.class)));
subquery.where(builder.and(
builder.equal(
subroot.get("item").get("id"),
root.get("item").get("id")),
builder.equal(
subroot.get("cell").get("store").as(Store.class),
store)));
Expression<Boolean> where = builder.equal(
root.get("id"),
subquery);
query.where(where);
return model.getList(query);
The incorrect SQL query produced is following:
SELECT t0.id, (...) FROM move t0 WHERE (t0.id = (
SELECT MAX(t1.id) FROM item t3, item t2, move t1
WHERE (((t2.id = t3.id) AND
(t1.cell_store = ?)) AND
((t2.id = t1.item_ref) AND
(t3.id = t0.item_ref))))
)
I do not understand why there is a double cross join in the subquery. Thank you for helping!