How can I write this SQL query as a Hibernate JPA Criteria (with Restrictions, etc) in Java ?
SELECT q.*
FROM queue AS q
WHERE q.executed = false AND
q.queued_on = (SELECT min(queued_on) FROM queue WHERE item_id = q.item_id);
I only managed to write the first part like this:
getBaseCriteria()
.add(Restrictions.eq("executed", false))
// Missing Second Where Filter Here
.addOrder(Order.asc("queuedOn"))
.list();
Try to create a separate criteria instance for the subquery and simply add as another restriction as follows:
DetachedCriteria subCriteria = DetachedCriteria.forClass(Queue.class, "sub")
.add(Restrictions.eqProperty("sub.itemId","main.itemId"))
.setProjection(Projections.projectionList().add(Projections.min("sub.queuedOn")));
session.createCriteria(Queue.class, "main")
.add(Subqueries.propertyEq("main.queuedOn", subCriteria ));
.add(Restrictions.eq("main.executed", false));
.addOrder(Order.asc("main.queuedOn"))
.list();
Related
I'm trying to write a CriteriaQuery which will query latest observation for each city. City is defined by city_code field, while latest record is defined by observation_time field.
I can easily write it in a plain SQL, but I cant understand how to do it with jpa criteria api.
select distinct m.* from
(select city_code cc, max(observation_time) mo
from observations group by city_code) mx, observations m
where m.city_code = mx.cc and m.observation_time = mx.mo`
It is possible when You are open for loose efficiency.
So first let's transform our query to logical equivalent one:
select distinct m.* from observations m where
m.observation_time = (select max(inn. observation_time) from observations inn
where inn.city_code = m.city_code);
then let's translate it to JPA CriteriaQuery:
public List<Observation> maxForEveryWithSubquery() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Observation> query = builder.createQuery(Observation.class);
Root<Observation> observation = query.from(Observation.class);
query.select(observation);
Subquery<LocalDateTime> subQuery = query.subquery(LocalDateTime.class);
Root<Observation> observationInner = subQuery.from(Observation.class);
subQuery.where(
builder.equal(
observation.get(Observation_.cityCode),
observationInner.get(Observation_.cityCode)
)
);
Subquery<LocalDateTime> subSelect = subQuery.select(builder.greatest(observationInner.get(Observation_.observationTime)));
query.where(
builder.equal(subSelect.getSelection(), observation.get(Observation_.observationTime))
);
TypedQuery<Observation> typedQuery = entityManager.createQuery(query);
return typedQuery.getResultList();
}
Unfortunately JPA does not support sub queries in FROM clause. You need to write a native query or use framework like FluentJPA.
I want to build a query like below using Hibernate Projections attribute. Can someone check the below. I have written java code like.
DetachedCriteria dCriteria = DetachedCriteria.forClass(FinancialYearQuater.class, "FinancialYearQuater");
dCriteria.add(Restrictions.eq("FinancialYearQuater.finYear", year));
dCriteria.addOrder(Order.asc("finYear"));
dCriteria.setResultTransformer(Projections.distinct(Projections.property("id")));
List<FinancialYearQuater> list = (List<FinancialYearQuater>) findAll(dCriteria);
Here's the SQL query:
select
distinct
this_.FINY_NAME,
this_.FINY_YEAR,
this_.QTR_NAME,
this_.QTR_NO,
this_.QTR_PERIOD
from
V_FINYR_QTR this_
where
this_.FINY_YEAR=2016
order by
this_.FINY_YEAR asc
I have written below code. Is that the correct way get the distinct data?
DetachedCriteria dCriteria = DetachedCriteria.forClass(FinancialYearQuater.class, "FinancialYearQuater");
dCriteria.add(Restrictions.eq("FinancialYearQuater.finYear", year));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("FinancialYearQuater.finYear"), "finYear");
projList.add(Projections.property("FinancialYearQuater.finYearName"), "finYearName");
projList.add(Projections.property("FinancialYearQuater.qtrNo"), "qtrNo");
projList.add(Projections.property("FinancialYearQuater.qtrPeriod"), "qtrPeriod");
dCriteria.setProjection(Projections.distinct(projList));
dCriteria.addOrder(Order.asc("finYear"));
List<FinancialYearQuater> list = (List<FinancialYearQuater>) findAll(dCriteria);
I'm trying to reproduce a SQL query containing self-joins using Hibernate. This is the SQL:
select cur.*
from first ft1,
first ft2,
second sc1,
second sc2,
third thd
where sc1.id = sc2.id
and sc1.idFirst = ft1.id
and sc2.idFirst = ft2.id
and ft1.is <> ft2.id
and ft1.id = thd.idFirst
and ft2.id = ?
I've tried using Criteria and DetachedCriteria as follows, by I'm not able to get it to work:
Criteria criteria = this.getSession().createCriteria(Third.class);
DetachedCriteria first1Criteria = DetachedCriteria.forClass(First.class);
first1Criteria.setProjection(Projections.property("id"));
DetachedCriteria first2Criteria = DetachedCriteria.forClass(First.class);
first2Criteria.setProjection(Projections.property("id"));
first2Criteria.add(Restrictions.eq("id", id)); // where id is passed in from the calling method
first2Criteria.getExecutableCriteria(getSession()).list();
DetachedCriteria second1Criteria = DetachedCriteria.forClass(Second.class);
second1Criteria.setProjection(Projections.property("id"));
DetachedCriteria second2Criteria = DetachedCriteria.forClass(Second.class);
second2Criteria.setProjection(Projections.property("id"));
second1Criteria.add(Property.forName("id.id").in(second2Criteria ));
second1Criteria.add(Property.forName("id.idFirst").in(first1Criteria));
second1Criteria.add(Property.forName("id.idFirst").in(first2Criteria));
first1Criteria.add(Property.forName("id").notIn(first2Criteria));
criteria.add(Property.forName("id").in(first1Criteria));
return criteria.list();
No exceptions are thrown in this case, but the query isn't actually executed. I've tried a few differnt combinations along these lines, but unsuccessfully. Any help is much apreciated!
I would like to use a hibernate criteria object as a subquery on a second criteria, like this:
DetachedCriteria latestStatusSubquery = DetachedCriteria.forClass(BatchStatus.class);
latestStatusSubquery.setProjection(Projections.projectionList()
.add( Projections.max("created"), "latestStatusDate")
.add( Projections.groupProperty("batch.id"))
);
DetachedCriteria batchCriteria = DetachedCriteria.forClass(BatchStatus.class).createAlias("batch", "batch");
batch.add( Property.forName( "created" ).eq( latestStatusSubquery ) );
The problem is that adding a groupProperty automatically add that property to the select clause on the subselect query and I can't find any way to stop this from happening.
The result, of course a DB error because the subquery returns too many values.
Does anyone know a way around this?
Try like below sample,
DetachedCriteria subquery = DetachedCriteria.forClass(CustomerCommentsVO.class, "latestComment");
subquery.setProjection(Projections.max("latestComment.commentId"));
subquery.add(Expression.eqProperty("latestComment.prospectiveCustomer.prospectiveCustomerId", "comment.prospectiveCustomer.prospectiveCustomerId"));
objCriteria = objSession.createCriteria(CustomerCommentsVO.class,"comment");
objCriteria.add(Subqueries.propertyEq("comment.commentId", subquery));
List lstComments = objCriteria.list();
java experts can you please help me write detached queries as a part of the criteria query for the following SQL statement.
select A.*
FROM AETABLE A
where not exists
(
select entryid
FROM AETABLE B
where B.classpk = A.classpk
and B.userid = A.userid
and B.modifiedDate > A.modifiedDate
)
and userid = 10146
You need to write a correlated subquery. Assuming property / class names match column / table names above:
DetachedCriteria subquery = DetachedCriteria.forClass(AETable.class, "b")
.add(Property.forName("b.classpk").eqProperty("a.classpk"))
.add(Property.forName("b.userid").eqProperty("a.userid"))
.add(Property.forName("b.modifiedDate").gtProperty("a.modifiedDate"));
Criteria criteria = session.createCriteria(AETable.class, "a")
.add(Property.forName("userid").eq(new Integer(10146)))
.add(Subqueries.notExists(subquery);
Just one addition to the above query. If the entryid is not the primary key, then you'll need to add projection.
DetachedCriteria subquery = DetachedCriteria.forClass(AETable.class, "b")
.add(Property.forName("b.classpk").eqProperty("a.classpk"))
.add(Property.forName("b.userid").eqProperty("a.userid"))
.add(Property.forName("b.modifiedDate").gtProperty("a.modifiedDate"))
.add(setProjection(Projections.property("entryId")); // Additional projection property
Criteria criteria = session.createCriteria(AETable.class, "a")
.add(Property.forName("userid").eq(new Integer(10146)))
.add(Subqueries.notExists(subquery);