Cannot issue data manipulation statements with executeQuery()
Solution 1:
To manipulate data you actually need executeUpdate()
rather than executeQuery()
.
Here's an extract from the executeUpdate()
javadoc which is already an answer at its own:
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Solution 2:
When executing DML statement , you should use executeUpdate
/execute
rather than executeQuery
.
Here is a brief comparison :
Solution 3:
If you're using spring boot, just add an @Modifying annotation.
@Modifying
@Query
(value = "UPDATE user SET middleName = 'Mudd' WHERE id = 1", nativeQuery = true)
void updateMiddleName();
Solution 4:
For Delete query - Use @Modifying
and @Transactional
before the @Query
like:-
@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {
@Modifying
@Transactional
@Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
void deleteCopyByTradeId(Integer id);
}
It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
error.
Edit:
Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.
@Transactional
By default, CRUD methods on repository instances are transactional. For read operations,
the transaction configuration readOnly flag is set to true.
All others are configured with a plain @Transactional so that default transaction
configuration applies.
@Modifying
Indicates a query method should be considered as modifying query as that changes the way
it needs to be executed. This annotation is only considered if used on query methods defined
through a Query annotation). It's not applied on custom implementation methods or queries
derived from the method name as they already have control over the underlying data access
APIs or specify if they are modifying by their name.
Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL
statements.