I have an example MyTable with 3 columns - id, common_id, creation_date, where common_id groups entries.
Now I would like to select using CriteriaBuilder all newest entries from each group (that is for each common_id get me latest creation_date).
In SQL the query would look like this:
select * from MyTable where (common_id, creation_date) in (select common_id, max(creation_date) from MyTable group by common_id)
Now I have tried to create the where predicate by writing something like (cb is CriteriaBuilder, root is a Root):
cb.array(root.get('common_id'), cb.max(root.get('creation_date')))
.in(
query.subquery(MyTable.class)
.select(cb.array(root.get('common_id'), cb.max(root.get('creation_date'))))
.groupBy(root.get('common_id')))
But unfortunately cb.array is not an Expression (it's a CompoundSelect), so I cannot use .in() on it.
Thanks for pointers!
could you create it using JPQL? As far that I know, that is not possible.
I looked at the Spect (4.6.16 Subqueries) and it talk about "simples select expression":
simple_select_clause ::= SELECT [DISTINCT] simple_select_expression
I believe that only one return is possible, if you look at the examples there you will not find anything like it.
You will need to use NativeQuery for it.
Related
I am new to Java and Querydsl. I have searched so much to get how to write the below query in query dsl. end up with nothing.Can any one please help.
SELECT * FROM `library_user_product` GROUP by user_id HAVING max(product_id)
Thanks in advance
Use this link it has examples for the group by, having and other function in respect to JPA
sample:
SELECT c.currency, SUM(c.population) FROM Country c
WHERE 'Europe' MEMBER OF c.continents
GROUP BY c.currency
HAVING COUNT(c) > 1
Does jOOQ support array of select query? I want something like the following:
select table.*, array(select another_table.id from another_table where ...)
from table;
I tried experimenting with DSL.array(context.select(...).asField()) but this generates array[(select ...)] instead of array(select(...)).
I should have done:
PostgresDSL.array(context.select(...))
Note that we are using PostgresDSL instead of the generic DSL and not applying .asField() to the select, to inline the inner select query into the outer query.
Here is my problem I am trying to add a Select query in where condition how can i achieve this in Jooq?
selectQuery.addFrom(DefaultInfo.DEFAULT_INFO);
selectQuery.addConditions(DefaultInfo.DEFAULT_INFO.FOLDER_TYPE=+"(Select FolderType From Folder Where Folder.FolderRSN = folderRSN )" );
I know this is wrong but how to add a Select Query output in another query where condition?
Use the Field.in(Select<? extends Record1<T>>) method on your column. For example:
DEFAULT_INFO.FOLDER_TYPE.in(
select(FOLDER.FOLDER_TYPE)
.from(FOLDER)
.where(FOLDER.FOLDER_RSN.eq("folderRSN"))
)
The IN predicate is documented in the manual, here:
http://www.jooq.org/doc/latest/manual/sql-building/conditional-expressions/in-predicate/
http://www.jooq.org/doc/latest/manual/sql-building/conditional-expressions/in-predicate-degree-n/
Hi I'm trying to select records from one table which doesn't have records in connected many-to-many table with specific values.
I will explain on sample tables:
documentation:
id_documentation
irrelevant_data
user:
id_user
irrelevant_data
documentation_user:
id_documentation
id_user
role
What I want to achieve is to select every single documentation which doesn't have user in specific role. Any ideas?
The main problem is that I'm using java's CriteriaBuilder to create query so using subqueries is impossible (I think).
You can add restrictions on your left join using: createAlias(java.lang.String, java.lang.String, int, org.hibernate.criterion.Criterion) method, see API.
Check this answer for an example on how to use the left join with a criteria.
Main problem does not exist - Criteria API do have SubQuery. Query itself selects instances of User and uses not in construct to limit results based to subquery. Subquery selects all users that are connected to document with specific role via DocumentationUser.
Try something like this (code not tested):
CriteriaQuery<Documentation> cq = cb.createQuery(Documentation.class);
Root<Documentation> u = cq.from(Documentation.class);
Subquery<Integer> sq = cq.subquery(Integer.class);
Root<User> su = sq.from(User.class);
sq.select(su.get("id_user"));
Join<User, DocumentationUser> du = su.join("documentationUserCollection");
sq.where(cb.equals(du.get("role"), "mySpecificRole"));
cq.where(cb.not(cb.in(u.get("id_user")).value(sq)));
See also this useful answer on SO.
In this query:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = cb.createTupleQuery();
// FROM GamePlayedEvent gpe
Root<GamePlayedEvent> gpe = q.from(GamePlayedEvent.class);
// SELECT gameId, COUNT(*) AS count, AVG(duration)
// AS avDur, AVG(rewardCurrency) AS avCur, AVG(rewardXP) avXp
q.select(cb.tuple(
gpe.<String>get("gameId"),
cb.count(gpe).alias("count"),
cb.avg(gpe.<Double>get("duration")).alias("avDur"),
cb.avg(gpe.<Integer>get("rewardCurrency")).alias("avCur"),
cb.avg(gpe.<Integer>get("rewardXp")).alias("avXp")
));
// WHERE loginTime BETWEEN ...
q.where(cb.between(gpe.<Date>get("time"), fromTime, toTime));
// GROUP BY gameId
q.groupBy(gpe.<String>get("gameId"));
// ORDER BY count DESC
q.orderBy(cb.desc(???));
How can I add the ORDER BY count DESC, referring to the "count" defined in the SELECT clause?
What if you just captured the count expression, and used it directly?
Expression event_count = cb.count(gpe);
q.select(cb.tuple(
gpe.<String>get("gameId"),
event_count,
...
));
q.orderBy(cb.desc(event_count));
I came across the same problem today but none of the suggested solutions worked for me because I needed to reuse the expression not only in the order by clause but also in the group by clause.
One obvious solution would be to create a view on the database level but this is a bit clumsy, creates an unnecessary subquery and even not possible if the db user isn't granted enough privileges. A better option which I ended up implementing is to write something like this
q.select(cb.tuple(
gpe.<String>get("gameId"),
cb.count(gpe),
...
)).groupBy(cb.literal(2)).orderBy(cb.literal(2));
The first downside of this approach is that the code is errorprone. The other drawback is that the generated sql query contains ordinal position notation, which works on some databases (like postgresql or mariadb) but doesn't work on others (like sql server). In my case, however, I found this to be the best option.
Tested on jpa 2.1 with hibernate 5.2.3 as a provider and postgresql 9.6.
Even though the Pro JPA 2 book describes that the alias method can be used to generate a sql query alias (on page 251) I have had no success with making it work with neither EclipseLink or Hibernate. For your question I would say that your orderBy line should read:
q.orderBy(cb.desc(cb.count(gpe));
if it was supported by the different vendors.
As far as my research goes it seams that the alias method is only used for naming elements in the tuble used in the select (so only for projection).
I have one question though. Why would you want to use the JPA Criteria API for this query. It (the query) seams to be static in nature so why not use JPQL where you can define your query aliases directly.
Have you tried setting up a projection with an alias?
criteria.setProjection(Projections.projectionList()
.add(Projections.count("item.id"), "countItems"));
criteria.addOrder(Order.desc("countItems"));
For a sum aggregation field I have the following code which worked for me:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entity);
Root<T> root = cq.from(entity);
cq.orderBy(cb.desc(cb.sum(root.get(orderByString))));
// orderByString is string entity field that is being aggregated and which we want to put in orderby clause as well.