'Could not extract ResultSet' error when using nativeQuery in JPA - java

I'm using JPARepository in SpringBoot and using the #Query annotation but I get an error
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
When using the nativeQuery=true
This is my function:
#Query(value = "select * from table1 where status = ?1 and time <= ?2 LIMIT 2", nativeQuery = true)
List<MyModel> findScheduledSmsMessages(Status status, LocalDateTime time);

I added the following code above my query and
#Modifying
#Transactional
Like this :
#Modifying
#Transactional
#Query(value = "DELETE FROM played_sheet WHERE user_id = ?1 AND sheet_music_id = ?2", nativeQuery = true)
void deleteByUserIdAndSheetMusicId(Integer userId,Integer sheetMusicId);

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.

SQLGrammarException: could not execute statement while trying to delete from db

I'm trying to solve a problem with statement deletion query. Now the implementation looks like this.
#Transactional
public void deleteStatements(LocalDate expiryDate) {
int deletedStatements = statementRepository.deleteByIdCreatedDateBefore(expiryDate);
logger.info("Deleted {} statements.", deletedStatements);
}
#Query(value = "WITH deleted AS (DELETE FROM generated_statements WHERE created_date < :expiryDate RETURNING id) " +
"SELECT count(*) FROM deleted;", nativeQuery = true)
int deleteByIdCreatedDateBefore(LocalDate expiryDate);
Now I'm getting this error:
could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
I tried adding #Modifying annotation, then I tried removing it, tried with various combinations of #Transactional and #Modifying, still got various errors regarding this deletion like:
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet or Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
Now I'm really not sure what is the problem here.
Replace your delete query with this
#Modifying
#Query(value = "DELETE FROM generated_statements WHERE created_date < :expiryDate", nativeQuery = true)
int deleteByIdCreatedDateBefore(LocalDate expiryDate);
or turn it directly into a JPQL/HQL query. No need for a nativeQuery. Example:
#Modifying
#Query(value = "DELETE FROM GeneratedStatement g WHERE g.createDate < :expiryDate")
int deleteByIdCreatedDateBefore(LocalDate expiryDate);
By specifying an int return value, you will automatically get the number of deleted rows.
Considering all this complex logic is to get number of deleted rows you can try just:
#Modifying
#Query("DELETE FROM generated_statements WHERE created_date < :expiryDate")
int deleteByIdCreatedDateBefore(LocalDate expiryDate);
or just using keywords(if your entity has createdDate attribute)
int deleteByCreatedDateBefore(LocalDate expiryDate);
#Modifying
#Query(value = "DELETE FROM generated_statements WHERE created_date < ?1", nativeQuery = true)
int deleteByIdCreatedDateBefore(LocalDate expiryDate);

Java Hibernate Create Native Query javax.persistence.TransactionRequiredException: Executing an update/delete query

I have this problem, using native query on Hibernate. This the query :
Query query = session.createSQLQuery(
"UPDATE InvoiceItems SET current_balance = '"+current_balance+"' WHERE record_id = '"+record_id+"'");
query.executeUpdate();
but i get this error when run the query :
javax.persistence.TransactionRequiredException: Executing an
update/delete query
any suggest ? i have try with this way : TransactionRequiredException Executing an update/delete query
You need a transaction.
Transaction txn = session.beginTransaction();
Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3");
updateQuery.setParameter(1, title);
updateQuery.setParameter(2, body);
updateQuery.setParameter(3, id);
updateQuery.executeUpdate();
txn.commit();
from https://www.baeldung.com/jpa-transaction-required-exception

Spring Boot: JPA QueryDSL: How to Make a Named Delete?

In the QueryDSL repository, I can make a named query in this way:
public interface HistoricalDataRepository
extends PagingAndSortingRepository<HistoricalData, Long>,
QueryDslPredicateExecutor<HistoricalData> {
List<HistoricalData> findAll(Predicate predicate);
HistoricalData findByKeyAndDate(String key, String date);
#Query(value = "SELECT * FROM historical_data h WHERE "
+ " h.key = :key "
+ " AND h.date <= :date "
+ " order by date desc"
+ " limit 1"
, nativeQuery = true)
HistoricalData myFindByKeyLowerOrEqualToDate(
#Param("key") String key
, #Param("date") Date date
);
How can I perform a
DELETE FROM HISTORICAL_DATA;
If I use the same syntax as above (with the #Queryannotation), I get an exception:
org.springframework.orm.jpa.JpaSystemException:
could not extract ResultSet; nested exception is
org.hibernate.exception.GenericJDBCException: could not extract ResultSet
Background: I do not want to use a
historicalDataRepository.deleteAll();
as this has a VERY low performance.
EDIT:
My syntax would look like the following:
#Query(value = "DELETE FROM HISTORICAL_DATA", nativeQuery = true)
void myDeleteAll();
Looks like, you are combining both JPA query as well as native query. For the syntax you have given, you have to specify it as native as shown below
#Query(value = "DELETE FROM HISTORICAL_DATA", nativeQuery = true)

Delete From JPA Query with Inner Join

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.

Categories