2012-04-05 13 views
0

私は単純なmysqlの挿入を行うメソッドを持っていますが、次のように挿入アクションをロールバックしようとしたときにエラーが発生しましたが、エラー時にはロールバックされません。ロールバックはJavaでは動作しません

public void addFamer(FamerDTO famer) throws Exception { 
     Connection con = JDBCConnectionPool.getInstance().checkOut(); 
     con.setAutoCommit(false); 

     try { 


      String generalFamerDataSQL = "INSERT INTO famers(famer_code, name_wt_initials, full_name, gender, " 
        + "nic_or_passport_no, sc_possition, phone_home, phone_mobile, phone_office) VALUES(?,?,?,?,?,?,?,?,?)"; 
      PreparedStatement insertFamerPS = con.prepareStatement(generalFamerDataSQL, PreparedStatement.RETURN_GENERATED_KEYS); 
      insertFamerPS.setString(1, famer.getFamerCode()); 
      insertFamerPS.setString(2, famer.getNameWithInitials()); 
      insertFamerPS.setString(3, famer.getNameInFull()); 
      insertFamerPS.setString(4, famer.getGender()); 
      insertFamerPS.setString(5, famer.getNICorPassportNo()); 
      insertFamerPS.setString(6, famer.getSocietyPosission()); 
      insertFamerPS.setString(7, famer.getHomePhone()); 
      insertFamerPS.setString(8, famer.getMobilePhone()); 
      insertFamerPS.setString(9, famer.getOfficePhone()); 
      insertFamerPS.execute(); 


String famerRelations = "INSERT INTO org_reg_blk_soc_fmr(org_id, region_id, famer_id, block_id, soc_id) " 
        + "VALUES (?,?,?,?,?)"; 
      PreparedStatement famerRelationsPS = con.prepareStatement(famerRelations); 
      famerRelationsPS.setInt(1, famer.getOrganization().getOrg_id()); 
      famerRelationsPS.setInt(2, famer.getRegion().getRegion_id()); 
      famerRelationsPS.setInt(3, famerID); 
      famerRelationsPS.setInt(4, famer.getBlock().getBlockId()); 
      famerRelationsPS.setInt(6, famer.getSociety().getSoc_id()); //intentionally made an error here to test, put index as 6 for 5 
      famerRelationsPS.execute(); 


      con.commit(); 
     } catch (Exception e) { 
      if (con != null) { 
       logger.info("Rolling back!"); 
       con.rollback();      
      } 
      logger.error(e.getLocalizedMessage()); 

     } finally { 
      con.setAutoCommit(true); 
      JDBCConnectionPool.getInstance().checkIn(con); 
     } 

    } 

このメソッドは、最初の挿入操作をロールバックすると予想される2番目の挿入文にエラーがあるため、必要なパラメータとともに呼び出されます。エラーが表示されたと考えて、レコードは最初の挿入ステートメントによってデータベースに追加されます。

+0

挿入する前に明示的に新しいトランザクションを開始しようとしましたか? –

答えて

7

あなたが使用しているテーブルタイプは何ですか?前回MySQLを使用したとき、MyISAMテーブルはトランザクションをサポートしていませんでした。つまり、別のテーブルタイプを使用する必要があります。 InnoDB。

+0

(-1を取り除いたもの)は、最初に尋ねる/見ているものです。 –

+0

多くのRory、MyISQLテーブルはMyISAMだったので、私はそれらをinnodbに変更してから動作します。 – Harsha

+0

@ハシャあなたの問題を解決したら、この回答を受け入れることを検討するべきです:) – Jim

関連する問題