Reputation: 3337
I have a front-end application with a JPA/JAX-RS backend, where i want to make a request to delete a comment on a post.
I'm using the repository pattern, where i have made the following method to delete a comment:
@Override
public Comment delete(Comment comment)
{
return getEntityManager().createQuery("DELETE Comment c WHERE c.id = :id ", Comment.class)
.setParameter("id", comment.getId())
.getSingleResult();
}
here i get the error:
Update/delete queries cannot be typed JPA
Here I'm a bit in doubt of what to do, i could just change the Comment.class and make it a generic query, but inside my facade, which calls the method
I also want to make a conditional check i there was a comment or not
Comment commentToDelete = commentRepository.get(comment);
if(commentToDelete == null){
throw new ResourceNotFoundException(Comment.class, comment);
}
how can i solve this problem in the easiest way, can i return an Object and just cast that, or is there another way to check for the comment and delete it from the database?
Upvotes: 0
Views: 208
Reputation: 15878
You missed FROM
in the query.
Change query to this DELETE FROM Comment c WHERE c.id = :id
by specifying FROM
Refer this
Upvotes: 1
Reputation: 3783
When you create a DELETE OR UPDATE query, you should always use executeUpdate method
getEntityManager().createQuery("DELETE FROM Comment c WHERE c.id = :id ", Comment.class)
.setParameter("id", comment.getId())
.executeUpdate();
The return type of this method is an integer telling you how many rows within your table have been affected
Upvotes: 1
Reputation: 73
You can omit the conditional check because as per getSingleResult() documentation if there is no result it will throw NoResultException
, you can just catch that exception and re-throw yours.
So solution would look something like this:
try {
Comment deletedComment = commentRepository.delete(comment);
} catch (NoResultException nre) {
throw new ResourceNotFoundException(Comment.class, comment)
}
Also make sure to add FROM
to your JPQL query as Alien said.
Edit:
I think you should call query.executeUpdate()
rather than calling getSingleResult()
;
Upvotes: 1