Search code examples
javaspringjpaentitymanagersql-delete

Update/delete queries cannot be typed JPA


I'm using the Spring framework for working on training projects. I'm also using JPA and have been having a hell of a time. In my DAO implementation class, I've written:

@Override
public void deleteEntries(Module mod) {
    System.out.println(mod.getDescription());
    entityManager.createQuery("delete from TrainingEntry e where e.module = :mod and e.completedDate IS NULL",
                              TrainingEntry.class).setParameter("mod", mod);

}

As you can see it's just a simple DELETE statement, but I get the error:

"Update/delete queries cannot be typed."

My guess is, that I need to use some of the EntityManager class methods to do the job, but I'm not certain, as there's next to nothing about this error online. I'm also having difficulty applying some solutions I've found online about JPA delete queries. Any point in the right direction or explanation as to why this error is thrown is much appreciated.


Solution

  • The declaration of the EntityManager methods are the following:

    Query createQuery(java.lang.String qlString)
    <T> TypedQuery<T> createQuery(java.lang.String qlString, java.lang.Class<T> resultClass)
    // The other three method is not relevant here
    

    From this, you can clearly see, that you get a TypedQuery<T> because of the second parameter. If you remove it, you will get a simple Query object. That is what you need.