Guest User

Untitled

a guest
Nov 7th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. package transactionwithlockex1.dao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.List;
  9.  
  10. import transactionwithlockex1.dto.SelectedItem;
  11.  
  12. public class StockDAO {
  13. // 定数
  14. private static final String CONNECTION_STR = "jdbc:oracle:thin:@//172.16.4.6:1521/infopdb";
  15. private static final String DB_USERNAME = "demo2017";
  16. private static final String DB_PASSWORD = "demo2017";
  17.  
  18. // 在庫数変更
  19. // 引数listの全商品の在庫数が変更できたら、コミット
  20. // もし1つでも在庫数が変更できない場合はロールバック
  21. public static boolean update(List<SelectedItem> list) throws SQLException
  22. {
  23. boolean result = true;
  24.  
  25. try(
  26. Connection con = DriverManager.getConnection(CONNECTION_STR, DB_USERNAME, DB_PASSWORD);
  27. )
  28. {
  29. // 自動コミットオフ
  30. con.setAutoCommit(false);
  31.  
  32. // preparedStatement用意
  33. PreparedStatement pstmt4Lock =
  34. con.prepareStatement("SELECT 在庫数 FROM 在庫管理_在庫データ WHERE 商品ID=? FOR UPDATE");
  35. PreparedStatement pstmt4Update =
  36. con.prepareStatement("UPDATE 在庫管理_在庫データ SET 在庫数=? WHERE 商品ID=?");
  37.  
  38. try
  39. {
  40. for(SelectedItem item : list)
  41. {
  42. // ロック
  43. pstmt4Lock.setInt(1, item.getId());
  44. int currentStock = 0;
  45. try( ResultSet rs = pstmt4Lock.executeQuery() )
  46. {
  47. if(rs.next())
  48. {
  49. currentStock = rs.getInt("在庫数");
  50. }
  51. } // ここでResultSetは自動的にclose()される
  52.  
  53. // 在庫数変更
  54. pstmt4Update.setInt(1,currentStock - item.getQuantity());
  55. pstmt4Update.setInt(2,item.getId());
  56.  
  57. pstmt4Update.executeUpdate();
  58. }
  59.  
  60. // ここまでこれたら全商品の在庫数変更成功
  61. con.commit();
  62. }
  63. catch(SQLException ex)
  64. {
  65. // DBアクセス時になんらかのエラー発生
  66. // まずはロールバック
  67. con.rollback();
  68.  
  69. // エラー原因に応じて対応
  70. // 在庫数が足りない => チェック制約違反(エラーコード:2290)発生
  71. if(ex.getErrorCode() == 2290)
  72. {
  73. result = false;
  74. }
  75. else
  76. {
  77. throw ex;
  78. }
  79. }
  80. }
  81.  
  82. return result;
  83. }
  84.  
  85.  
  86. }
Add Comment
Please, Sign In to add comment