在休眠中创建保存点和回滚

时间:2013-09-18 12:08:00

标签: hibernate

如果在hibernate中发生异常,如何创建保存点以及如何使用回滚我知道它在jdbc中是如何工作的但我在hibernate程序中遇到了创建保存点的问题。

我的程序是'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();
}

} } “ 他们是学生类,id和name作为属性,setter和getter方法作为持久化类。我在哪里获得连接变量..我是hibernate的新手。

2 个答案:

答案 0 :(得分:1)

要实现savepoint,您需要实现Work界面。在实现中,您将执行自定义任务,如更新数据库等。

Work work = new Work() {
    public void execute(Connection arg0) throws SQLException {
             //custom task
    }
};

电话

  

session.doWork(工作)

如果有任何例外情况,请致电

  

connection.rollback(工作)

答案 1 :(得分:0)

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);
    }
  });
}