Hibernate criteria restriction on multiple criterias - java

I am writing a Criteria query. My query is on multiple criterias corresponding to tables property and user. It returns the result if prop is 12 or 13 no matter who the user is OR if prop is NULL then user must be loggedInUser.
The Sql query has where condition as follows which returns 4 rows
where (property.PROP in (12,13) or (property.PROP is null
and user.loggedInUser = 'XYZ'))
My criteria
Criteria userQuery = session.createCriteria(User.class);
Criteria propertyQuery = userQuery .createCriteria("property");
Criterion crt = (Criterion) userQuery.add(Restrictions.eq("loggedInUser", userId));
propertyQuery.add(
Restrictions.or(
Restrictions.in("prop",propList),
Restrictions.and(Restrictions.isNull("prop"),crt)
)
);
My issue is that Restrictions.and(criterion,criterion) takes two criterion as parameter. However, the second criterion 'crt' on userQuery is not valid when type casted (Criterion). Hibernate will give error. How can I achieve this functionality in Criteria. or how to write criteria Restrictions.and(Restrictions.isNull("prop") , userQuery.add(Restrictions.eq("loggedInUser", userId)))

Use Joins using hibernate criteria as below example code:
List cats = session.createCriteria(Cat.class)
.createAlias("kittens", "kit")
.add( Restrictions.like("kit.name", "Iz%") )
.list();
Note: The code above is just an example of how to use Join in hibernate criteria.

Related

How to select distinct table from joined tables with Hibernate Criteria API?

I'm trying to implement a query like this:
SELECT DISTINCT C.* FROM A
join B on A.some_id = B.some_id
join C on B.some_id = C.some_id;
With Hibernate Criteria API.
I need to have distinct results for whole C table, not just for some column(s) of it.
I tried to do like that:
Criteria criteria = createCriteria(C.class, "ct")
.createCriteria("B", "bt")
.createCriteria("A", "at")
.//Some restrictions which are applied to all tables
And like that:
Criteria criteria = createCriteria(A.class, "at")
.createCriteria("B", "bt")
.createCriteria("C", "ct")
.//Some restrictions which are applied to all tables
(I don't see a difference though).
Tried to ad ResultTransformer:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Tried to put all colums into ProjectionsList and then:
criteria.setProjection(Projections.distinct(projectionList));
But that projection only adds "distinct" keyword to first column in list but not to whole table.
What I want to achieve - is something like that:
criteria.setProjection(Projections.distinct("C.*"));
but I only can add a column here, can't use wildcards like in query.
Any help is greatly appreciated.
You should select columns from table 'C' not from table 'A' like below.
SELECT distinct (*) FROM C
it can be written in hibernate criteria as follows:
Criteria criteria = session.createCriteria(C.class);
criteria = criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
ResultTransformer rt = new DistinctRootEntityResultTransformer();
List list = rt.transformList(criteria.list());

Hibernate Criteria filter Entity where ManyToMany relation contains multiple objects

I need help with Hibernate Criteria API.
I have a class Job that contain a list of Skill in ManyToMany relationship.
I need to select jobs based on a skill list given as parameter.
I've tried with Restriction.in("skill.id",ids) but this gives me wrong list.If i've selected 2 skills in search form i want the jobs that contain BOTH of them,so i need somehow to implement AND clause.
I've tried with Conjunction:
Conjunction and = Restrictions.conjunction();
for(Skill skill:job.getSkills()){
and.add(Restrictions.eq("skill.id",skill.getId()));
}
And this:
Criteria crit = criteria.createCriteria("skills",JoinType.LEFT_OUTER_JOIN);
for(Skill skill:job.getSkills()){
crit.add(Restrictions.eq("id", skill.getId()));
}
but it creates same alias for skill and it gives me no result.
sql is and (skill1_.ID=? and skill1_.ID=?)
Can anyone help me with this ?thanks
UPDATE:
HQL Query will be like:
select a from Job a where exists (select skill1.id from Skill skill1 join skill1.jobs r where r.id=a.id and skill1.id=1) and exists (select skill2.id from Skill skill2 join skill2.jobs r where r.id=a.id and skill2.id=4)
I need Criteria based on this.
for(Skill skill:job.getSkills()){
DetachedCriteria subquery = DetachedCriteria.forClass(Skill.class,"skill");
subquery.add(Restrictions.eq("id",skill.getId()));
subquery.setProjection(Projections.property("id"));
subquery.createAlias("jobs", "job");
subquery.add(Restrictions.eqProperty("job.id", "Job.id"));
criteria.add(Subqueries.exists(subquery));
}
I managed to solve it.now it works perfect.

Hibernate Criteria join to table containing foreign key

I have two tables:
Client (clientId, firstName, lastName, gender)
Event (clientId, eventId)
I need to represent a query similar to the following using Criteria:
SELECT c.clientId, c.firstName, c.lastName, c.gender, MAX(eventId)
FROM Client c JOIN Event e ON c.clientId = e.clientId
GROUP BY c.clientId, c.firstName, c.lastName, c.gender
I have tried this:
final Criteria criteria = session.createCriteria(Client.class);
criteria.setFetchMode("Event", FetchMode.JOIN);
criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("clientId")).add(Projections.max("eventId")));
but it throws an exception on the last line with the message:
HibernateQueryException: could not resolve property: eventId of:
Client
How can I specify the join between the Client table which itself contains no column related to the Event table but the clientId column on the Event table is a foreign key back into the Client table?
As you can see, it's really driven off the Client table and that I only need to select the maximum eventId from the Event table. Also, as I mentioned, I am trying to make a change to an existing Criteria query which is based on the Client class. It is used to retrieve all the columns for all active clients. I just need to add one extra column to the query results - the maximum eventId.
Use alias
Criteria criteria = session.createCriteria(Event.class, "et").
createAlias("et.Client", "ct").
setProjection(Projections.projectionList().
add(Projections.groupProperty("et.clientId")).
add(Projections.max("et.eventId")));
For more details on criteria, refer Criteria Queries
That is obvious. Because Client class does not have eventId property, and your criteria is defined for Client class.
When trying to use a property of B class inside a Criteria for A, you have to use Aliases.
All you have to do is to modify your code like this:
final Criteria criteria = session.createCriteria(Event.class, "event");
criteria.createAlias("event.client", "client");
criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("clientId")).add(Projections.max("eventId")));
UPDATED (based on your comment)
As your query needs Event class, you have to have a Criteria for this class. So you have to something like this:
final Criteria criteria = session.createCriteria(Event.class, "event");
criteria.createAlias("event.client", "client");
//The criteria below, is returning clientId
DetachedCriteria eventCr = DetachedCriteria.forClass(Event.class, "event");
eventCr.setProjection(Projections.projectionList().add(Projections.groupProperty("clientId")).add(Projections.max("eventId")));
//Now using subqueries you can achieve your goal
criteria.add(Subqueries.propertyIn("clientId", eventCr));
I don't know for sure what you're looking for, but I hope I have given you some good hints. You might want to try Subqueries.propertyEq instead if your query must return a single id.

Get record with max id, using Hibernate Criteria

Using Hibernate's Criteria API, I want to select the record within a table with the maximum value for a given column.
I tried to use Projections, creating an alias for max(colunName), then using it in restrictions.eq(), but it keeps telling me "invalid number".
What's the correct way to do that with Hibernate?
You can use a DetachedCriteria to express a subquery, something like this:
DetachedCriteria maxId = DetachedCriteria.forClass(Foo.class)
.setProjection( Projections.max("id") );
session.createCriteria(Foo.class)
.add( Property.forName("id").eq(maxId) )
.list();
References
Hibernate Core Reference Guide
15.8. Detached queries and subqueries
I found that using addOrder and setMaxResults together worked for me.
Criteria c = session.createCriteria(Thingy.class);
c.addOrder(Order.desc("id"));
c.setMaxResults(1);
return (Thingy)c.uniqueResult();
Using the MySQL dialect, this generates a SQL prepared statement about like this (snipping out some of the fields):
select this_.id ... from Thingy this_ order by this_.id desc limit ?
I am not sure if this solution would be effective for dialects other than MySQL.
Use
addOrder(Order.desc("id"))
and fetch just the first result :)
HQL:
from Person where person.id = (select max(id) from Person)
Untested. Your database needs to understand subselects in the where clause.
Too lazy to find out if/how such a subselect can be expressed with the criteria api. Of course, you could do two queries: First fetch the max id, then the entity with that id.
The cleaner solution would also be :
DetachedCriteria criteria = DetachedCriteria.forClass(Foo.class).setProjection(Projections.max("id"));
Foo fooObj =(Foo) criteria.getExecutableCriteria(getCurrentSession()).list().get(0);
Date maxDateFromDB = null;
Session session = (Session) entityManager.getDelegate();
//Register is and Entity and assume maxDateFromDB is a column.
//Status is another entity with Enum Applied.
//Code is the Parameter for One to One Relation between Register and Profile entity.
Criteria criteria = session.createCriteria(Register.class).setProjection(Projections.max("maxDateFromDB") )
.add(Restrictions.eq("status.id", Status.Name.APPLIED.instance().getId()));
if(code != null && code > 0) {
criteria.add(Restrictions.eq("profile.id", code));
}
List<Date> list = criteria.list();
if(!CollectionUtils.isEmpty(list)){
maxDateFromDB = list.get(0);
}
To do it entirely with Detached Criteria (because I like to construct the detached criteria without a session)
DetachedCriteria maxQuery = DetachedCriteria.forClass(Foo.class)
.setProjection( Projections.max("id") );
DetachedCriteria recordQuery = DetachedCriteria.forClass(Foo.class)
.add(Property.forName("id").eq(maxId) );
For the max() function in hibernate:
criteria.setProjection(Projections.max("e.encounterId"));

Hibernate subquery

I have a problem in creating subqueries with Hibernate. Unfortunately the Subqueries class is almost entirely undocumented, so I have absolutely no clue how to convert the following SQL into a Hibernate Criteria:
SELECT id
FROM car_parts
WHERE car_id IN ( SELECT id FROM cars WHERE owner_id = 123 )
I was hoping the following would 'just work':
session.createCriteria(CarParts.class).add(eq("car.owner", myCarOwner));
but unfortunately it does not. So it seems I actually have to use the Subqueries class to create the Criteria. But I was unable to find a reasonable example though Google, so that leads me to asking it here.
Try Like this:
Table details): Category (id, name, desc, parentId, active)
DetachedCriteria subCriteria = DetachedCriteria
.forClass(Category.class);
subCriteria.add(Restrictions.isNull("parent"));
subCriteria.add(Restrictions.eq("active", Boolean.TRUE));
subCriteria.add(Restrictions.eq("name", categoryName));
subCriteria.setProjection(Projections.property("id"));
Criteria criteria = getSession().createCriteria(Category.class);
criteria.add(Restrictions.eq("active", Boolean.TRUE));
criteria.add(Subqueries.propertyEq("parent", subCriteria));
It will generate the query like:
select
*
from
Categories this_
where
this_.active=1
and this_.parentId = (
select
this0__.id as y0_
from
Categories this0__
where
this0__.parentId is null
and this0__.active=1
and this0__.name='Health Plan'
)
Good Luck!
-Rohtash Singh
Try to create an alias for the "car" property before adding the eq expression like this:
session.createCriteria(CarParts.class)
.createAlias("car", "c")
.add(eq("c.owner", myCarOwner));
As first check the ORM configuration between Car and CarPart entities, usually you need the setup the relationship between them. After that try to execute the following code:
List result = session.createQuery("from " + CarPart.class.getName() +
" as parts join parts.car as car where car.owner = :myOwner")
.setParameter("myOwner", 123)
.list();

Categories

Resources