Currently I'm working on a "filter"-function for a customer list.
I have this following subquery and I'm not sure if there is a way to build this with the CriteriaBuilder. It would also work without the multiselect b.date, ... but I need Group By, Order By and Limit in order to select the min value. The result should be a single number.
SELECT (COALESCE(SUM(b.account1),0) + COALESCE(SUM(b.account2),0) + COALESCE(SUM(b.deposits),0)) AS SUM FROM customer_balance b WHERE b.client_nr = '123455'
GROUP BY b.date
ORDER BY SUM
LIMIT 1
e.g. Customer Balance Table
"client_nr","date","account1","account2","deposits"
"1234567","2018-02-28",204600.0,82500.0,21120.0
UPDATE:
This is my code currently, but
Subquery<BigDecimal> CustomerBalanceSubQuery = CustomerQuery.subquery(BigDecimal.class);
Root<CustomerBalance> CustomerBalance = CustomerBalanceSubQuery.from(CustomerBalance.class);
Expression<BigDecimal> currentAccount = criteriaBuilder.sum(CustomerBalance.get("currentAccount"));
Expression<BigDecimal> overnightDeposits = criteriaBuilder.sum(CustomerBalance.get("overnightDeposits"));
Expression<BigDecimal> termDeposits = criteriaBuilder.sum(CustomerBalance.get("termDeposits"));
CustomerBalanceSubQuery.select(criteriaBuilder.sum(termDeposits, criteriaBuilder.sum(overnightDeposits, currentAccount)));
Predicate predicate = criteriaBuilder.equal(CustomerBalance.get("id").get("ClientNr"), Customer.get("ClientNr"));
CustomerBalanceSubQuery.where(predicate);
// adding to main-query
queryPredicateList.add(criteriaBuilder.and(criteriaBuilder.greaterThan(CustomerBalanceSubQuery, BigDecimal.valueOf(liquidity))));
How can I add orderBy for my subquery?
How can I set maxResult?
Thanks!
B
After talking to some colleagues I refactored the query to:
SELECT min(COALESCE(b.current_account,0) + COALESCE(b.overnight_deposits,0) + COALESCE(b.term_deposits,0)) FROM customer_balance b WHERE b.client_nr = '123456'
And the code...
Subquery<BigDecimal> customerBalanceSubQuery = customerQuery.subquery(BigDecimal.class);
Root<CustomerBalance> customerBalance = customerBalanceSubQuery.from(CustomerBalance.class);
Expression<BigDecimal> currentAccount = customerBalance.get("currentAccount");
Expression<BigDecimal> overnightDeposits = customerBalance.get("overnightDeposits");
Expression<BigDecimal> termDeposits = customerBalance.get("termDeposits");
customerBalanceSubQuery.select(criteriaBuilder.min(criteriaBuilder.sum(termDeposits, criteriaBuilder.sum(overnightDeposits, currentAccount))));
Predicate predicate = criteriaBuilder.equal(customerBalance.get("id").get("clientNr"), customer.get("clientNr"));
customerBalanceSubQuery.where(predicate);
queryPredicateList.add(criteriaBuilder.and(criteriaBuilder.greaterThan(CustomerBalanceSubQuery, BigDecimal.valueOf(liquidity))));
Anyway, it would be interesting to see the query from the original question.
Other than #BillyFrost mentioned, I'm not sure if every sql query is buildable with the Criteria API.
Related
I want to ask, how to make a query order by not in in java, this is the query, thank you:
select * from $table_name order by id not in
(select r.transaction_id from $child_table r where r.transaction_id is not null) desc;
Session session = HibernateUtil.getHibernateSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<PARENT_ENTITY> cr = cb.createQuery(<PARENT_ENTITY>.class);
Root<PARENT_ENTITY> root = cr.from(PARENT_ENTITY.class);
CriteriaQuery<PARENT_ENTITY> cr_child = cb.createQuery(<CHILD_ENTITY>.class);
Root<CHILD_ENTITY> child_root = cr_child.from(CHILD_ENTITY.class);
cr.select(root).where(cb.isNotNull(child_root.get("transaction_id")));
Please try to fill the values for entities as per requirement, hope this helps
Is it possible to do orderby expression using linq query expression based on dynamic string parameter? because the query i have is producing weird SQL query
my linq:
var product = from prod in _context.Products
join cat in _context.Categories on prod.CategoryId equals cat.CategoryId
join sup in _context.Suppliers on prod.SupplierId equals sup.SupplierId
orderby sortParam
select new ProductViewModel
{
ProductName = prod.ProductName,
ProductId = prod.ProductId,
QuantityPerUnit = prod.QuantityPerUnit,
ReorderLevel = prod.ReorderLevel,
UnitsOnOrder = prod.UnitsOnOrder,
UnitPrice = prod.UnitPrice,
UnitsInStock = prod.UnitsInStock,
Discontinued = prod.Discontinued,
Category = cat.CategoryName,
Supplier = sup.CompanyName,
CategoryId = cat.CategoryId,
SupplierId = sup.SupplierId
};
where var sortParam = "prod.ProductName"
The code above produces weird sql where order by sortParam is being converted to (SELECT 1). Full query catched by sql profiler below:
exec sp_executesql N'SELECT [prod].[ProductName], [prod].[ProductID], [prod].[QuantityPerUnit], [prod].[ReorderLevel], [prod].[UnitsOnOrder], [prod].[UnitPrice], [prod].[UnitsInStock], [prod].[Discontinued], [cat].[CategoryName] AS [Category], [sup].[CompanyName] AS [Supplier], [cat].[CategoryID], [sup].[SupplierID]
FROM [Products] AS [prod]
INNER JOIN [Categories] AS [cat] ON [prod].[CategoryID] = [cat].[CategoryID]
INNER JOIN [Suppliers] AS [sup] ON [prod].[SupplierID] = [sup].[SupplierID]
ORDER BY (SELECT 1)
OFFSET #__p_1 ROWS FETCH NEXT #__p_2 ROWS ONLY',N'#__p_1 int,#__p_2 int',#__p_1=0,#__p_2=10
I'm seeing a lot of people doing linq order by using dynamic parameter but all of them use lambda not query expression, please enlighten me
As was already mentioned, you are passing a string value instead of an expression that reflects the column name. There are options for what you want however, see for example here.
I have the following criteria query, which retrieves some fields from Anfrage and Sparte entities and also the translated string for the sparte.i18nKey.
This works as expected if I dont use orderBy.
Now I have the requirement to sort by the translated string for sparte.i18nKey and using the orderBy as shown below, results in QuerySyntaxException: unexpected AST node
So the problem must be the subselect in the orderBy clause!
select distinct new
my.domain.model.dto.AnfrageDTO(
anfrage0.id,
anfrage0.name,
anfrage0.sparte.id,
anfrage0.sparte.i18nKey,
-- retrieve translated string for sparte.i18nKey
(select rb0.value from at.luxbau.mis2.domain.model.ResourceBundleEntity as rb0
where (anfrage0.sparte.i18nKey = rb0.key) and (rb0.language = 'de'))
)
from my.domain.model.impl.Anfrage as anfrage0
left join anfrage0.sparte as sparte
order by (
-- sort by translated string for sparte.i18nKey
select rb1.value
from my.domain.model.ResourceBundleEntity as rb1
where (anfrage0.sparte.i18nKey = rb1.key) and (rb1.language = 'de')
) asc
My Java code looks like this:
private List<AnfrageDTO> getAnfragen() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<AnfrageDTO> query = cb.createQuery(AnfrageDTO.class);
Root<Anfrage> anfrage = query.from(Anfrage.class);
anfrage.join(Anfrage_.sparte, JoinType.LEFT);
query.select(cb.construct(AnfrageDTO.class,
anfrage.get(Anfrage_.id),
anfrage.get(Anfrage_.name),
anfrage.get(Anfrage_.sparte).get(Sparte_.id),
anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey),
// create subquery for translated sparte.i18nKey
createResourceBundleSubQuery(cb, query, anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey)).getSelection()));
TypedQuery<AnfrageDTO> tq = entityManager
.createQuery(query)
// use subquery to sort by translated sparte.i18nKey
.orderBy(cb.asc(createResourceBundleSubQuery(cb, query, anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey))));
tq.setMaxResults(10);
List<AnfrageDTO> anfragen = tq.getResultList();
return anfragen;
}
public Subquery<String> createResourceBundleSubQuery(CriteriaBuilder cb, CriteriaQuery<?> query, <String> expr) {
Subquery<String> subquery = query.subquery(String.class);
Root<ResourceBundleEntity> rb = subquery.from(ResourceBundleEntity.class);
subquery
.select(rb.get(ResourceBundleEntity_.value))
.where(cb.and(
cb.equal(expr, rb.get(ResourceBundleEntity_.key)),
cb.equal(rb.get(ResourceBundleEntity_.language), "de")));
return subquery;
}
Using a native SQL query with subselect in orderBy works also as expected.
select distinct
anfrage0_.id,
anfrage0_.name,
anfrage0_.sparte_id,
sparte4_.i18n_key,
(select rb3.i18n_value from resource_bundle rb3 where rb3.language_code = 'de' and rb3.i18n_key = sparte4_.i18n_key) as sparte_i18n_value
from
mis2.anfrage anfrage0_
left outer join mis2.sparte sparte4_ on anfrage0_.sparte_id = sparte4_.id
order by (
select rb.i18n_value
from mis2.resource_bundle rb
where sparte4_.i18n_key = rb.i18n_key and rb.language_code = 'de'
) asc
Also using an alias in the native SQL query works also as expected.
select distinct
anfrage0_.id,
anfrage0_.name,
anfrage0_.sparte_id,
sparte4_.i18n_key,
(select rb3.i18n_value from resource_bundle rb3 where rb3.language_code = 'de' and rb3.i18n_key = sparte4_.i18n_key) as sparte_i18n_value
from
mis2.anfrage anfrage0_
left outer join mis2.sparte sparte4_ on anfrage0_.sparte_id = sparte4_.id
order by sparte_i18n_value
asc
It would be great if JPA Criteria API would support using an alias in orderBy clause!
Any hints welcome - Thank you!
My environment is WildFly 11 and PostgreSQL 9.6.
JPA doesn't support passing parameter in order by clause, your problem has been asked before: Hibernate Named Query Order By parameter
There are two update queries and 1st update query execute successfully but 2nd update query is not execute and show the following message:
Msg 512, Level 16, State 1, Line 10
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.
1st update query:
update dbo.TblPrePostApproval
set
dbo.TblPrePostApproval.PAApprovedDate = (select dbo.TblMasterInfo.AppRefDate
from dbo.TblMasterInfo
Where dbo.TblMasterInfo.Appid = dbo.TblPrePostApproval.Appid),
dbo.TblPrePostApproval.PAApprovedTenor = '36',
dbo.TblPrePostApproval.PAApprovedAmt = (select dbo.TblMasterInfo.AppReqeustAmt
from dbo.TblMasterInfo
where dbo.TblPrePostApproval.Appid = dbo.TblMasterInfo.AppID),
dbo.TblPrePostApproval.PADisbBr = (select dbo.TblMasterInfo.AppSourceBrName
from dbo.TblMasterInfo
where dbo.TblPrePostApproval.Appid = dbo.TblMasterInfo.AppID)
2nd update query
update dbo.TblPrePostApproval
set
dbo.TblPrePostApproval.PAApprovedDate = (select dbo.TestPost.PADate
from dbo.TestPost
Where dbo.TestPost.Appid = dbo.TblPrePostApproval.Appid),
dbo.TblPrePostApproval.PAApprovedTenor = (select dbo.TestPost.PATenor
from dbo.TestPost
Where dbo.TestPost.Appid = dbo.TblPrePostApproval.Appid),
dbo.TblPrePostApproval.PAApprovedAmt = (select dbo.TestPost.PAAmt
from dbo.TestPost
where dbo.TestPost.Appid = dbo.TblPrePostApproval.AppID),
dbo.TblPrePostApproval.PADisbBr = (select dbo.TestPost.PABr
from dbo.TestPost
where dbo.TestPost.Appid = dbo.TblPrePostApproval.AppID)
Where is my problem? Pls any one suggest me.
One of your subqueries (I guess on line 10) is returning more than one row, so it can't check to see if it equals anything, because it's a set, not a value. Just change your query to be more specific. Try adding LIMIT 0, 1 to the end of the subqueries, or TOP (1) after the the SELECT in each subquery.
Why don't you use JOINs for your update? Much easier to read and understand!
Query #1:
UPDATE ppa
SET
PAApprovedDate = info.AppRefDate,
PAApprovedTenor = '36',
PAApprovedAmt = info.AppReqeustAmt,
PADisbBr = info.AppSourceBrName
FROM
dbo.TblPrePostApproval ppa
INNER JOIN
dbo.TblMasterInfo.TblMasterInfo info ON info.Appid = ppa.Appid
Query #2:
UPDATE ppa
SET
PAApprovedDate = tp.PADate,
PAApprovedTenor = tp.PATenor,
PAApprovedAmt = tp.PAAmt,
PADisbBr = tp.PABr
FROM
dbo.TblPrePostApproval ppa
INNER JOIN
dbo.TestPost tp ON tp.Appid = ppa.AppID
I'd like to do a query than in sql it's:
SELECT users.id, SUM(total), SUM(total*price) FROM sales INNER JOIN users ON sales.id_user=users.id GROUP BY users.id
I tried searching for the solution, but the closest I get was:
QSales sales = QSales.sales;
JPAQuery query = from(sales);
QUsers users = QUsers.users;
query.innerJoin(sales.users, users);
List<Object[]> response = query.groupBy(sales.user).list(sales.user, sales.total.sum());
but i don't know how to get this:
SUM(total*price)
SUM(total*price)
can be expressed as
total.multiply(price).sum()
you can use NumberExpression
NumberExpression totalPrice = sales.total.multiply(sales.price);
then use totalPrice.sum()