Reputation: 555
How to create a savepoint and how to use rollback if exception occurs in hibernate I know how it works in jdbc but i got stuck creating savepoint in hibernate program.
My program is 'public class StudentStoredData { public static void main(String[] args) {
String name = " ";
int count = 0;
int cond = 0;
// creating configuration object
Configuration cfg = new Configuration();
cfg.configure("Student.cfg.xml");// populates the data of the configuration file
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
try {
do {
Scanner scn = new Scanner(System.in);
System.out.println("enter 1 to insert and 0 to quit");
cond = scn.nextInt();
if (cond == 0)
break;
Student e1 = new Student();
System.out.println("Enter Id ");
int id = scn.nextInt();
e1.setId(id);
System.out.println("Enter name ");
name = scn.next();
e1.setName(name);
session.persist(e1);// persisting the object
System.out.println("successfully saved");
t.commit();
} while (cond != 0);
} catch (Exception e) {
System.out.println("error occured in saving values . rolling back the recent changes");
} finally {
session.close();
}
} } ' Their is student class with id and name as attribute and setter and getter method as persistent class. Where do i get the connection variable .. I am new to hibernate .
Upvotes: 1
Views: 6263
Reputation: 924
Savepoint savepoint = null;
try{
person.setPersonName("John");
session.update(person);
session.flush();
savepoint = setSavepoint("savepoint_1");
}catch(Exception e){
System.out.println("Exception occured rolling back to save point");
rollbackSavepoint(savepoint);
}
private Savepoint savepoint;
public Savepoint setSavepoint(final String savePoint) {
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
savepoint = connection.setSavepoint(savePoint);
}
});
return savepoint;
}
public void rollbackSavepoint(final Savepoint savepoint) {
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
connection.rollback(savepoint);
}
});
}
Upvotes: 0
Reputation: 1567
For implementing savepoint, you need to implement Work interface. In the implementation , you would do your custom tasks like updating database etc.
Work work = new Work() {
public void execute(Connection arg0) throws SQLException {
//custom task
}
};
The call
session.doWork(work)
And if there is any exxception just call
connection.rollback(work)
Upvotes: 1