0

I know that the following code will delete the record with id = 5 from database:

 Query query = session.createQuery("delete from Class where id = 5");
 query.executeUpdate();

But before i delete it, need to save this record's data in a variable. So I want to select id = 5, and after some code, I delete it. It's not efficient if i use two distinct query for them. Because in this way we search database for this item two times.

query = session.createQuery("from Class where id = 5");
//somecode
query = session.createQuery("delete Class where id = 5");
...

So i need a more efficient way to do this, and do it better.

4
  • 2
    It would be nice to explain why you think this is not a good way of coding it. Otherwise it just seems like another "give me code that works" question. Commented Jul 4, 2012 at 10:42
  • yes, it's right. i did'n want to code like them, because, it must search in database 2 times. but in the answers right method for this task is explained. Commented Jul 4, 2012 at 11:09
  • 2
    I know, however my point still stands, you state that its a bad idea to do it that way but never explained why you thought that. Commented Jul 4, 2012 at 11:33
  • @JonTaylor he said: Because in this way we search database for this item two times. Commented Dec 26, 2013 at 14:45

2 Answers 2

4

No need to create query to delete a record.

query = session.createQuery("from Class where id = 5");
List list=query.list();
if(list.size()!=0)
 {
   ClassName obj = (ClassName)list.get(0);
   session.delete(obj);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

In addition, if this 'id' field is the @Id you can use session.get() to obtain your object in place of session.createQuery.
3

Hibernate has a Session.delete() method. Use it if you already have a reference to the entity to remove. No need for a query.

This would also apply the potential cascades configured on associations, which a delete query does not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.