*Write a hibernate application to delete the records from product table whose productID is 11.

To delete the records from hibernate we can use two approaches.

Approach 1

Load the record and mark the object as to delete.
 Program:
 
public class DeleteRecords{
public static void main(String[] args){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Product p = new Product();
hsession.load(p,11);     // step 1
hsession.delete(p);      // step 2
tx.commit();                 // step 3
hsession.close();
             }
}


Step 1: when step 1 is executed it has retrieve the records whose primary key value is 11 and add into 1st level cache.

Step 2: When we call the method object is marked as to be deleted.

Step 3: when we call the commit method the hibernate software got the delete query and replaces the positional parameter with primary key value and send the query to database server.

Note:In this approach first we are checked in whether the record is available or not if the record is not available. The load() method throws object not found exception.

0 comments:

Post a Comment