【问题标题】:Creating savepoint and rollingback in hibernate在休眠中创建保存点和回滚
【发布时间】:2013-09-23 04:35:30
【问题描述】:

如果在休眠中发生异常,如何创建保存点以及如何使用回滚我知道它在 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 方法作为持久类。我在哪里得到连接变量..我是休眠的新手。

【问题讨论】:

    标签: hibernate


    【解决方案1】:

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

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

    电话

    session.doWork(工作)

    如果有任何异常,请致电

    connection.rollback(工作)

    【讨论】:

      【解决方案2】:
      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);
          }
        });
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-16
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        相关资源
        最近更新 更多