0

I keep trying to create a user and delete it afterwards as a part of my tests, but I keep getting the same error org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations even after continuously changing the code in both my Repository and Controller.

This is the code in my Repository:

@Transactional
    @Override
    public void deleteById(long id) {
        Query query = entityManager.createQuery(
                "delete from UserModel as u where u.id=:id"
        ).setParameter("id", id);
        query.getSingleResult();
        query.executeUpdate();
    }

This is the code in my Controller:

    @DeleteMapping("/deleteUser")
    public @ResponseBody
    void deleteUser(@RequestParam long id) {
        userRepository.deleteById(id);
        ResponseEntity.ok(null);
    }
Soufghalb
  • 13
  • 7
  • Does this answer your question? [JpaRepository Not supported for DML operations \[delete query\]](https://stackoverflow.com/questions/44022076/jparepository-not-supported-for-dml-operations-delete-query) – Martín Zaragoza Jun 12 '22 at 18:04
  • Sadly no, that is a whole different approach than mine – Soufghalb Jun 12 '22 at 18:25

1 Answers1

0

I think the exception is triggering due to the query.getSingleResult(); line which is trying to fetch a result from a DELETE query (which is an UPDATE type of query).

Try changing the code like this:

@Override
public void deleteById(long id) {
    Query query = entityManager.createQuery(
            "delete from UserModel as u where u.id=:id"
    ).setParameter("id", id);
    query.executeUpdate();
}
Martín Zaragoza
  • 1,717
  • 8
  • 19
  • I get a different error message when trying that, it then changes into a EmptyResultDataAccesException with the commentary that there is no entity found for query – Soufghalb Jun 13 '22 at 00:11
  • I suspect the entity being deleted does not exist in the database. Try inserting a row manually into the database , copy its ID and then test this code by feeding said ID value into the method. – Martín Zaragoza Jun 13 '22 at 09:07
  • I have tried the query in MySQL and it does work so I don't think the query is the problem – Soufghalb Jun 13 '22 at 16:46