I'm trying to translate a MySQL query to JPA.
I'm using MySQL5 and EclipseLink 2.4.2.
Here's the MySQL query :
SELECT s.id, s.startDate, CAST(GROUP_CONCAT(DISTINCT s.endDate ORDER BY s.date DESC) AS DATE) endDate
FROM table_s s
WHERE ...
GROUP BY s.id, s.startDate
id and date are primary key. They are represented by an embeddable id in JPA and fields are also readable in the entity (insertable/updatable = false).
Here's the JPA query :
SELECT s.id, s.startDate, SQL('CAST(GROUP_CONCAT(DISTINCT ? ORDER BY ? DESC) AS DATE)', s.endDate, s.date) AS endDate
FROM EntityS s
WHERE ...
GROUP BY s.id, s.startDate
The current issue is that the generated sql query does not include s.startDate for a reason I don't know.
If I simply change the code to SELECT s.id, s.startDate, s.endDate, it's working... but I really need to get the last endDate.
I tried MAX(s.endDate) but actually it does not give the last value (even if it currently works, it's not correct and can send a wrong result)
If someone got an idea or a solution, I would be pleased.
Ok, I made it otherwise :
SELECT s.id, s.startDate, s.endDate
FROM EntityS s
WHERE ...
AND s.date = (
SELECT MAX(s.date)
FROM EntityS s2
WHERE s2.id = s.id
AND s2.startDate = s.startDate
AND ...
)
GROUP BY s.id, s.startDate
Related
I have a query like below:
select * from Products p where ? between p.effctDate and p.expDate
Can I translate the above query to a spring data jpa query method? Like for example:
findByProductId(productId)
or I only have to use #Query or a Named query to handle such types of queries. I tried searching here first before asking the question as well as spring data site but did not find any solution. any help is appreciated.
You could use the following query:
Date date = //Input date
List<Product> = findByEffctDateAfterAndExpDateBefore(date, date);
Note that you have to enter date twice to match both 'where' clauses. This is under the assumption you are using Date objects, not literal Strings.
See JPA Repositories Table 2.3 for more info.
You can try to use something like below :
List findAllByDateApprovedBetween(String dateApprovedFrom, String dateApprovedTo);
It translates to :
Hibernate: select applicatio0_.id as id1_1_, applicatio0_.date_approved as date_app4_1_ from application applicatio0_ where (applicatio0_.date_approved between ? and ?)
You can try something like this trick:
select
p
from
Product p
where
(?1 = 'field1' and p.field1 between p.effctDate and p.expDate)
or (?1 = 'field2' and p.field2 between p.effctDate and p.expDate)
or (?1 = 'field3' and p.field3 between p.effctDate and p.expDate)
or (?1 = 'field4' and p.field4 between p.effctDate and p.expDate)
...
But this is not the best approach IMO...
To build dynamic queries you can use thees ones:
Specifications
Query by Example
Querydsl Extension
So, I want to get list of entities with count of specific data from my db. I use QueryDSL 4.1.3 and postgres. I have subquery, which counts specific data for each entity. I got something like this and it works:
JPAQuery<?> countQuery = from(sideEntity)
.join(..).on(..)
..
.select(sideEntity.countDistinct);
JPAQuery<?> mainQuery = from(mainEntity)
.innerJoin(..).on(..)
..
.where(..);
return mainQuery(mainEntity, countQuery).fetch();
What I need is to order by countQuery result. Following sql works on my db
select distinct
t0.id as a1
..
(select count(distinct (t2.id) from .. where .. ) as countAlias
from .. where ..
group by ..
order by countAlias desc
So I want to know if it's possible in queryDSL to set an alias to subquery result and then order by this alias.
How would represent the following Oracle SQL in Hibernate HQL.
select table_num
, room_id
, min(event_type) keep(dense_rank first order by changed_on desc)
from room_history
group by table_num, room_id;
The idea behind the query is to order the table "room_history" by "changed_on" datetime column and then group it by "table_num" and "room_id" pairs whilest keeping the first "event_type" for each group. The mentioned query works for Oracle but I have trouble converting it into HQL.
Purpose is to get the latest "event_type" for "table_num" and "room_id" pair.
It seems this is not achievable
I ended up converting the following SQL query instead. It is not perfect but it does the job for my purposes.
select table_num, event_type et from room_history where id in (select max(id) from privacy_history group by msisdn);
I was able to do this assumptions since when for this table always a.id > b.id then also a.changed_on> b.changed_on.
I am trying to get distinct values from table application based on the column entry_id. I've managed to get this working with plain SQL:
SELECT DISTINCT ON (a.entry_id) a.* FROM application AS a
JOIN entry AS e ON e.id = a.entry_id
WHERE e.valid_until BETWEEN ? AND ?;
The problem is, I have to translate it to HQL. Is there any way to resolve it in HQL without Criteria API?
It looks like this feature has been requested a long time ago but is still unresolved.
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();