Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why there is no delete by id in JPA?

 
Hong Anderson
Ranch Hand
Posts: 1936
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I curious why there is no delete by id in JPA?
So if I know id and want to delete I need to find first then delete, it's unnecessary to me.

Does anybody know the reason?
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kengkaj, Kengkaj, Kengkaj! Stop thinking like an SQL developer!

JPA is based on Objects, like Java. We don't just throw around numeric ids and column names. We are Java people!

The delete method takes an object. You just pass in an object. Which object do you want to delete? Just pass it in. Does it have a composite key, a sequence generated key, a numeric key or text key? [b]We don't care, we are Java developers.

Of course, the object we pass in will have an id in it. It will also be of a certain type of class. So, JPA, given the class, and the object that will obviously have an id embedded somwhere inside of it, can delete the underlying data, be it from one table, or spread across multiple tables, as those uncouth database designers are loath to do.

To be honest, if you just want to delete a row, given an id, you can do something like this:



That basically just passes an empty object with an id to the EntityManager or Hibernate Session for an immediate delete.

Think objects, my dear boy, objects!

-Cameron McKenzie



 
Hong Anderson
Ranch Hand
Posts: 1936
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cameron Wallace McKenzie wrote:
To be honest, if you just want to delete a row, given an id, you can do something like this:



That basically just passes an empty object with an id to the EntityManager or Hibernate Session for an immediate delete.

-Cameron McKenzie

I'm no expert in ORM, but I don't think it will work in JPA, EntityManager.remove throws IllegalArgumentException - if not an entity or if a detached entity.
http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#remove(java.lang.Object)

Can Hibernate do that?

Anyway, I'm not convinced by the reason think objects, using your logic, JPA should not have find by id?
If we want to find an object which we know its id, we need to create an empty object, set id to it, and pass to a find method? Not make sense to me. And JPA doesn't do that, it has a find by id method.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic