Saturday 15 March 2008

What are the other alternatives for session.load in hibernate to get single object(row) from database?

Generally when we want to delete any row from database using hibernate, we first load the object using session.load(Class,Long). We then delete the object retrieved for id using session.remove(object).

The problem with this approach is that Hibernate first fires a select query to the database to get the object(row). After it gets the object hibernate then fires a delete query to delete the row. So, do one operation on database, we are making hibernate to fire two queries.

Also another problem associated with this approach is that if the object of class(Table) which we want to delete may have join to other tables. In such scenario, when we are loading the object using session.load the join query is fired which is heavy.

The ideal approach would be create a hibernate query for deleting the object(row). In this approach hibernate will only fire single delete query. As only one query if fired, the time taken taken would be less.

eg:

Normal approach to delete using hibernate
MyTable table= (MyTable)session.load(MYTable.class,new Long(2);
session.remove(table);
session.flush();
session.close();

IDeal Approach to delete single row using hibernate
session.createQuery("delete from MyTable where id=2").executeUpdate();
session.fluch();
session.close();

No comments: