1

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

我的程序是'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 方法作为持久类。我在哪里得到连接变量..我是休眠的新手。

4

2 回答 2

1

要实现保存点,您需要实现 Work 接口。在实现中,您将执行自定义任务,例如更新数据库等。

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

通话

session.doWork(工作)

如果有任何异常,请致电

连接.回滚(工作)

于 2013-09-18T12:34:12.297 回答
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);
    }
  });
}
于 2018-11-25T07:49:06.767 回答