How do I write the following MySQL query using JPA Criteria?
select * from deptors where customerId in
(select customerId from address where zipcode="12345-6789")
and gender="male";
I have read http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria#Subquery and many stackoverflow threads including JPA 2.0, Criteria API, Subqueries, In Expressions. But I am just not getting it. Thanks for helping.
Something like:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Deptors> cq = cb.createQuery(Deptors.class);
Root<Deptors> c = cq.from(Deptors.class);
Subquery<Address> subquery = cq.subquery(Address.class);
Root<Address> a = subquery.from(Address.class);
However I would rather recommend building this query with JPQL and/or externalize it as a NamedQuery into your Entity.
Sebastian
Related
I'm having a complex SQL query which I want to execute in my Spring boot application. Following is a part of it's JPQL equivalent:
SELECT j FROM Job j WHERE
( (?6 = 0L) OR
0L IN (SELECT i12.filterFieldId FROM IjpPublishFilterFields i12 WHERE i12.jobId = j.id AND i12.fieldType LIKE 'GRADE') OR
(?6 IN (SELECT node.id FROM Grade node
INNER JOIN Grade parent ON ((node.lft BETWEEN parent.lft AND parent.rgt) AND
parent.id IN (SELECT i1.filterFieldId FROM IjpPublishFilterFields i1 WHERE **j.id** = i1.jobId AND i1.fieldType LIKE 'GRADE'))
WHERE node.organizationId = ?5 AND
node.isActive = true AND
parent.isActive = true )))
Since there are multiple other conditions which require to form 'Where' clause dynamically, I believe #Query annotation is out of the window.
After a lot of research, still I'm unable to convert this where clause to Specification.
e.g., I can return whole IjpPublishFilterFields object but can't return just i12.filterFieldId.
How could I write the where clause using JPA Specification?
I was able to solve this by using EnitityManager.createQuery() and formed this equivalent JPQL using simple String concatenation. Still I believe, we should be able to form this where caluse using Spring data JPA Specifications. So, further hints are welcomed.
There is nothing special about your query, so you should be able to translate this to something like criteriaBuilder.or( criteriaBuilder.eq(param, 0L), criteriaBuilder.literal(0L).in(subquery1), param.in(subquery2) ) where subquery1 and subquery2 are constructed roughly like this: Subquery<Long> subquery1 = criteriaQuery.subquery(Long.class); Root<IjpPublishFilterFields> r = subquery1.from(IjpPublishFilterFields.class); subquery1.select(r.get("filterFieldId")); ...
My query is :
SELECT * FROM drivers INNER JOIN vehicle ON drivers.vehicle_id = vehicle.id INNER JOIN cartype ON vehicle.cartype_id = cartype.id WHERE drivers.status = "free" AND vehicle.cartype_id = 1
Convert this query into laravel eloquent query .
I've tried harder but can't achieve !
Since we don't know what models and relationship between them you have - here is pure Query Builder request (pure translation of your sql, even if join with cartype table is redundant):
$result = DB::table("drivers")
->where("drivers.status", "free")
->join("vehicle", "drivers.vehicle_id", "=", "vehicle.id")
->join("cartype", "vehicle.cartype_id", "=", "cartype.id")
->where("vehicle.cartype_id", 1)->get()
Source: documentation, API page.
I have the following query, the problem that hibernate does not support nested after the 'from' I tried to create a view, but it did not work, I want to know how can I use hibernate to run this query correctly
SELECT sum(dc.nbrDefaut) def, a.nb control,c.id_of
FROM controlequalite c ,detailscontrole dc,
(select sum(nbreControlle) nb, id_monitrice
from controlequalite group by id_monitrice) a
where c.id = dc.id_controle
and c.id_monitrice = a.id_monitrice
and c.date >= '2016-03-25 00:00:00'
group by c.id_monitrice,c.id_of;
With a query like this, the simplest way is to use a native query. I'm assuming you are using JPA/Hibernate as ORM, so you can simply do like:
List<YourObject> resultList = yourEntityManager.createNativeQuery("nativeSQLhere", YourObject.class).getResultList();
Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete operation i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the command line query for select is
SELECT * FROM EmpData WHERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate?
please help,thanks in advance..
Query query = session.createQuery("from Resource where emplteam = :team");
query.setParameter("team", "Team1");
List list = query.list();
emplteam should be the property of your class Resource , not your database column's name.
I guess it is simple using HQL .
String hql = "FROM Resource E WHERE E.emplteam = team1";
Query query = session.createQuery(hql);
List results = query.list();
Hope this helps
Note: Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
have you tried using criteria api?
Criteria crit = sessionFactory.getCurrentSession()
.createCriteria(EmpData.class).add(Restrictions.eq("EMPLTEAM", "teamxxx");
List<EmpData> result = crit.list();
For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");
Hi I want to get the count of this linq query.Im using entity framework with repository pattern.
It is possible to get the result by queryUserWalls.ToList().Count()
which I think is inefficient.
Can any body help.
var queryUserWalls = (from participation in _eventParticipationRepository.GetAll()
join eve in _eventRepository.GetAll() on participation.EventId equals eve.Id
join userWall in _userWallRepository.GetAll() on participation.EventId equals userWall.EventId
where participation.UserId == userId
select userWall.Id)
.Union(from userWall in _userWallRepository.GetAll()
select userWall.Id);
Leave out the ToList because it forces query execution. You want to use Queryable.Count, not Enumerable.Count. Then, it will execute on the server.