Delete From JPA Query with Inner Join - java

I keep getting errors when trying to get this SQL correct for a JPA repository delete. What is the correct syntax?
#Query("delete * from TS t inner join TSC c ON t.tenantId = c.id where t.id= ?1 AND c.endDate < ?2")
void deleteTSWithExpiredDate(Long id, Date date);
Caused by: java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
Another
#Query("delete t.* from TS t inner join TSC c ON t.tenantId = c.id where t.id= ?1 AND c.endDate < ?2")
void deleteTSWithExpiredDate(Long id, Date date);
expecting IDENT, found '*' near line 1, column 10 [delete t.*
Another
#Query("delete t from TS t inner join TSC c ON t.tenantId = c.id where t.id= ?1 AND c.endDate < ?2")
void deleteTSWithExpiredDate(Long id, Date date);
unexpected token: from near line 1, column 10 [delete t

The syntax for bulk delete is:
Query q = session.createQuery("delete Entity where id = :idParam");
// set params here
q.executeUpdate();
However from Hibernate documentation, no joins can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the sub-queries themselves can contain joins.

Related

Pagination on Native sql query gives : unexpected token: ON

While writing a pagination query in repository as below code segment, I'm getting following error.
Code
#Repository
public interface Aaaa extends PagingAndSortingRepository<TxnDealerInventoryItem, Long> {
#Query(value = "SELECT EM.PART_NO, EM.PART_NAME FROM TXN_DEALER_INVENTORY_ITEM E INNER JOIN MST_PRODUCT EM ON E.PRODUCT_ID = EM.PRODUCT_ID WHERE E.ACCOUNT_ID= :accountId AND EM.ALLOW_SERIAL_NUM = :isSerialized ORDER BY ?#{#pageable}",
countQuery = "SELECT COUNT(*) FROM TXN_DEALER_INVENTORY_ITEM E INNER JOIN MST_PRODUCT EM ON E.PRODUCT_ID = EM.PRODUCT_ID WHERE E.ACCOUNT_ID= :accountId AND EM.ALLOW_SERIAL_NUM = :isSerialized",
nativeQuery = true)
Page<Object[]> getNonSerializedDeviceList(#Param("accountId") Long accountId, #Param("isSerialized") String isSerialized, Pageable pageable);
}
Error
HQL: SELECT COUNT(*) FROM TXN_DEALER_INVENTORY_ITEM E INNER JOIN MST_PRODUCT EM ON E.PRODUCT_ID = EM.PRODUCT_ID WHERE E.ACCOUNT_ID= :accountId AND EM.ALLOW_SERIAL_NUM = :isSerialized
2023-02-10 18:52:52,753 ERROR [org.hibernate.hql.internal.ast.ErrorCounter] (http-/127.0.0.1:8881-1) line 1:76: unexpected token: ON
Native Query doesn't have any error when run from sql developer.
Framework versions are as follows, Unfortunately I'cant update these any further as there are limitations in deployment environment. You inputs are highly welcome on this !!
<spring.version>4.3.30.RELEASE</spring.version>
<spring.data.version>1.11.23.RELEASE</spring.data.version>
<hibernate.version>4.2.18.Final</hibernate.version>
PS : for testing purpose when I change the SQL to a very basic like a select *, It gives following error.
org.hibernate.hql.internal.ast.QuerySyntaxException: TXN_DEALER_INVENTORY_ITEM is not mapped [SELECT COUNT(*) FROM TXN_DEALER_INVENTORY_ITEM E ]
Got the problem resolved by removing the count query and make the return type to a List of object Array instead of Page as below code segment.
#Repository
public interface Aaaa extends PagingAndSortingRepository<TxnDealerInventoryItem, Long> {
#Query(value = "SELECT EM.PART_NO, EM.PART_NAME FROM TXN_DEALER_INVENTORY_ITEM E INNER JOIN MST_PRODUCT EM ON E.PRODUCT_ID = EM.PRODUCT_ID WHERE E.ACCOUNT_ID= :accountId AND EM.ALLOW_SERIAL_NUM = :isSerialized ORDER BY ?#{#pageable}",
nativeQuery = true)
List<Object[]> getNonSerializedDeviceList(#Param("accountId") Long accountId, #Param("isSerialized") String isSerialized, Pageable pageable);
}
Finally having good old Paginations :) Thanks everyone who looked into this.

How select distinct value with pageable Spring data JPA?

I want to make a distinct select in my table with pagination, but it is claiming this error. Does anyone know how to solve it?
org.postgresql.util.PSQLException: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
#Query(value = "SELECT DISTINCT budget.* FROM budget LEFT JOIN user_budget ON budget.id = user_budget.budget_id ORDER BY budget.created DESC, ?#{#pageable}",
countQuery = "SELECT DISTINCT count(*) FROM budget LEFT JOIN user_budget ON budget.id = user_budget.budget_id",
nativeQuery = true)
public Page<Budget> findAllByfilter(Pageable pageable);

Spring Data JPA #Query annotation, nativeQuery = true,

I have problem with my #Repository:
#Repository
public interface RekvZmRepository extends CrudRepository<RekvalZamestn, RekvalZamestnPk> {
#Query(value = "SELECT z.* FROM rek_zm d INNER JOIN proj_a a ON d.id = a.prj_idcislo"
+ " INNER JOIN proj_e e ON a.id = e.id"
+ " INNER JOIN rekv_z z ON d.id = z.id"
+ "WHERE d.id = ?1 AND a.id = ?2 AND e.id = ?3", nativeQuery = true)
public List<RekvalZamestn> getRekvOsOnDoh(Long dhzmrk, Long prj, Long prje);
}
When I run it, result is:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not
extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
When I run SQL it works, so for me it looks like problem is not with SQL but with my #Query.
Your query, in one-line format (condensing multiple spaces to one space for reasons of, erm, space), equates to
SELECT z.* FROM rek_zm d INNER JOIN proj_a a ON d.id = a.prj_idcislo INNER JOIN proj_e e ON a.id = e.id INNER JOIN rekv_z z ON d.id = z.idWHERE d.id = ?1 AND a.id = ?2 AND e.id = ?3
If you concatenate all the strings in one line like this, it becomes obvious that you are missing a space before the WHERE clause.
change SELECT z.* FROM to SELECT z FROM assuming RekvalZamestn class maps to table rekv_z.

Can I add amounts from multiple tables in hql

I would like to perform a query in HQL similar to this in SQL:
SELECT (
SELECT COUNT(*) FROM EMPLOYER +
SELECT COUNT(*) FROM COMPANIES
)
FROM DUAL
When I add "FROM DUAL" to the query I get an error:
org.hibernate.hql.ast.QuerySyntaxException: DUAL is not mapped
And if I leave off the "FROM DUAL" I get:
org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree
Any recommendations?
In SQL, subqueries need their own set of parentheses, so try this:
SELECT ((SELECT COUNT(*) FROM EMPLOYER) +
(SELECT COUNT(*) FROM COMPANIES)
)
If that doesn't work, resort to a from clause:
SELECT e.cnt + c.cnt
FROM (SELECT COUNT(*) as cnt FROM EMPLOYER
) e CROSS JOIN +
(SELECT COUNT(*) as cnt
FROM COMPANIES
) c
Since you didn't join the Company and Employee tables you'd better run two queries:
int companyCount = ((Number) getSession().createQuery("select count(*) from Company").uniqueResult()).intValue();
int employeeCount = ((Number) getSession().createQuery("select count(*) from Employee").uniqueResult()).intValue();
int totalCount = companyCount + employeeCount;
The (Number) is needed since PostgreSQL returns a BigInteger while HDSQLDB returns an Integer, but both are subclasses of Number.

Hibernate HQL issue expecting IDENT found "*"

I need get all data from relative table so I'm using something like this (i would use it in sql)
private static final String SELECT_OOPR_TO_SEND = "SELECT R.* " +
"FROM offerOrderProjectRel R, offerOrder O, project P " +
"WHERE P.id = R.project_id and O.id = R.offer_order_id " +
"and O.type = 'ORDER' and (P.status = 'PENDING' or P.status ='PROTECTED')" ;
;
#SuppressWarnings("unchecked")
public List<OfferOrderProjectRel> findAllOfferOrderToSendToSalesmans() {
Query q = getSession().createQuery(SELECT_OOPR_TO_SEND);
List<OfferOrderProjectRel> list = q.list();
return list;
}
After lauching this code i'm getting that error :
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT,
found '**' near line 1, column 10 [SELECT R.* FROM offerOrderProjectRel
R, offerOrder O, project P WHERE P.id = R.project_id and O.id =
R.offer_order_id and O.type = 'ORDER' and (P.status = 'PENDING' or
P.status ='PROTECTED')]
So how can I obtain all data from column R with hibernate?
The method createQuery expects an HQL query string.
HQL is an object-oriented querying language.
HQL interprets SELECT R.* as select the member field * of the object R.
But * is not a member field of R. Is it?..
To select all the member fields of R use:
SELECT R
FROM offerOrderProjectRel R, offerOrder O, project P
WHERE P.id = R.project_id and O.id = R.offer_order_id
and O.type = 'ORDER' and (P.status = 'PENDING' or P.status ='PROTECTED')
you use SQL query, not hql query, so it should be
Query q = getSession().createSQLQuery(SELECT_OOPR_TO_SEND);
For people that received the "expecting IDENT found “*”" error when using org.springframework.data.jpa.repository.Query and found this question I'll add that you can change the nativeQuery flag to true:
#Query(value = "SELECT * FROM table1", nativeQuery = true)
List<Object> myFindAll();

Categories