QueryDSL Group By Row Count - java

I'm stuck in get the total count of group by query result.
JPAQuery jpaQuery = new JPAQuery(entityManager);
jpaQuery.from(QMessageSend.messageSend)
.where(predicate)
.groupBy(QMessageSend.messageSend.messageId).count();
this is my current code.
and this code return count for each group.
SELECT count(*)
FROM MESSAGE_SEND ms
GROUP BY ms.MESSAGE_ID
but I want to get the total count of group by query result.
like result of below sql
SELECT count(*)
FROM (
SELECT *
FROM MESSAGE_SEND ms
GROUP BY ms.MESSAGE_ID
) msc
What I should do?
MESSAGE_ID is not primary key.
and JPAQuery's distinct method not support select specific column. (has no parameter)

I think you want COUNT(DISTINCT):
SELECT COUNT(DISTINCT s.MESSAGE_ID)
FROM MESSAGE_SEND ms;
If MESSAGE_ID is the primary key in the table, then COUNT(*) suffices.

Related

Inserting value in middle table in sqlite

I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:
Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT
This is my code:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')
Each of the queries must be enclosed inside parantheses:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10'
);
This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.
The statement can also be written without the VALUES clause, with SELECT:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10';

How to retrieve data and count of data at same time in hql?

I want to retrieve count and list of data in one query only which I want to write on JPA repository. I wrote it using a constructor and executed using entity manager, but it didn't work. It gave me a QuerySyntaxException. Here is my query:
String hql = "select new core.abc(select count(*) from abc as m where m.Id in :Ids and m.Type = :Type,"
+ "select max(m.modificationTime) from abc as m where m.Id in :Ids and m.Type = :Type )";
How can I write such kind of query in JPA repository?
I just figure out your use case senario is that you want to get all records from table as well as total-count of records and max value of a specific column , you named that column as modificationTime. So onething will be happen in this case, if you want to intract with table with single query, Than you will get useless data for both column named as max and count.
Try This for JPA,
#Query(value="SELECT cb from abc cd where cd.Id in (?1) and cd.Type=?2 , (SELECT MAX(m.modificationTime) as maxModificationTime , COUNT(*) as count FROM abc m where m.Id in (?3) and m.Type=?4) as m",nativeQuery=true)

remove duplicate Data after Execute SelectQuery in mutliple Tables

i have Three tables [users,projects,scenarios] i need to get latest update projects details based on modified Date column with out duplicate values
the tables are:
users Table :
project table
scenario Table
and i try below query but its return duplicates values if am using group by then old values came but i need latest values
With out Group by query
SELECT
p.`PROJECT_NAME`,
p.`CREATED_DATE`,
s.`MODIFIED_DATE`
FROM
`projects` p
JOIN `scenarios` s ON
s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
P.`USER_ID` =(
SELECT
USER_ID
FROM
users
WHERE
EMAIL = 'test#gmail.com'
)
ORDER BY
s.`MODIFIED_DATE`
DESC
out put:
with Group by Query :
SELECT
p.`PROJECT_NAME`,
p.`CREATED_DATE`,
s.`MODIFIED_DATE`
FROM
`projects` p
JOIN `scenarios` s ON
s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
P.`USER_ID` =(
SELECT
USER_ID
FROM
users
WHERE
EMAIL = 'test#gmail.com'
)
group by p.PROJECT_NAME
ORDER BY
s.`MODIFIED_DATE`
DESC
output:
You can separately get the latest scenario per project using a subquery then the resulting rows will then be join again to get the other columns, if needed.
SELECT p.PROJECT_NAME,
p.CREATED_DATE,
s.MODIFIED_DATE
-- all columns in s.* will have the latest row
FROM projects p
INNER JOIN scenarios s
ON p.PROJECT_ID = s.PROJECT_ID
INNER JOIN
(
SELECT project_ID, MAX(modified_date) MAX_modified_date
FROM scenarios
GROUP BY project_ID
) t ON s.project_ID = t.project_ID
AND s.modified_date = t.MAX_modified_date
INNER JOIN users u
ON P.USER_ID = u.USER_ID
WHERE u.EMAIL = 'test#gmail.com'
ORDER BY s.MODIFIED_DATE DESC
However, if you don't need to get the other columns, you can directly use MAX() and GROUP BY.
SELECT p.PROJECT_NAME,
p.CREATED_DATE,
MAX(s.MODIFIED_DATE) AS MAX_MODIFIED_DATE
FROM projects p
INNER JOIN scenarios s
ON p.PROJECT_ID = s.PROJECT_ID
INNER JOIN users u
ON P.USER_ID = u.USER_ID
WHERE u.EMAIL = 'test#gmail.com'
GROUP BY p.PROJECT_NAME,
p.CREATED_DATE
ORDER BY MAX_MODIFIED_DATE DESC

Hibernate Criteria create a count query without asking it beside The query

I create a query using criteria (java) on PostgreSQL DB ,
This is a snippet from my code:
protected Criteria createEntityCriteria() {
return createEntityCriteria(getSession());
}
protected Criteria createEntityCriteria(Session session) {
return session.createCriteria(getEntityClass(), "main").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}
Criteria crit = createEntityCriteria();
crit.setFirstResult((pagingInfo.getPageNumber() - 1) * pagingInfo.getPageSize());
crit.setMaxResults(pagingInfo.getPageSize());
now when i view the log from hibernate(criteria query) i see 2 queries
the first one:
the first query which i have NOT asked at all is:
/* criteria query */ select
count(*) as y0_
from some_Table this
left outer join moreTable
on ......
the second one is which i did asked for:
Hibernate:
/* criteria query */ select col1 y0_,
col2 y1_,
......
from .....
left join ....
on ....
order by
y41_ desc limit ? offset ?
the problem is that the count query fail due to a query time out .
and second one works perfect .
is there a way to prevent from hibernate to "made-up" this count query ?

Count number of group by rows in hibernate with criteria

I want to count the number of group by rows with hibernate Criteria API, but i can only count number of rows aggregated in each group:
ProjectionList projectionList = Projections.projectionList()
.add(Projections.groupProperty("color"))
.add(Projections.rowCount());
Criteria criteria = session.createCriteria("ProductEntity");
criteria.setProjection(projectionList);
// adding some criteria
List results = criteria.list();
Above code will results in this query:
select p.color, count(*) from product p group by p.color
But i want this query:
select count(*) from (select p.color from product p group by p.color)
I know it's possible with HQL, but i don't want to use it. So how can i do this with Criteria API?
If you want to know how many different colors are present you should use
Projections.countDistinct("color")
This will result a query which will return the same result as this:
select count(*) from (select p.color from product p group by p.color)

Categories

Resources