1 /** 2 * 根据表名生成该表的序列 3 * @param tableName 4 * @return 返回生成的序列 5 */ 6 //全局方法 -加锁 7 //public static synchronized int generate(String tableName) { 8 //局部成员方法-加锁 9 //public synchronized int generate(String tableName) { 10 //synchronized(this) { 11 public static int generate(String tableName) { 12 //使用数据库的悲观锁for update 13 String sql = "select value from t_table_id where table_name=? for update"; 14 Connection conn = null; 15 PreparedStatement pstmt = null; 16 ResultSet rs = null; 17 int value = 0; 18 try { 19 conn = DbUtil.getConnection(); 20 //开始事务 21 DbUtil.beginTransaction(conn); 22 pstmt = conn.prepareStatement(sql); 23 pstmt.setString(1, tableName); 24 rs = pstmt.executeQuery(); 25 if (!rs.next()) { 26 throw new RuntimeException(); 27 } 28 value = rs.getInt("value"); 29 value++; //自加 30 modifyValueField(conn, tableName, value); 31 //提交事务 32 DbUtil.commitTransaction(conn); 33 }catch(Exception e) { 34 e.printStackTrace(); 35 //回滚事务 36 DbUtil.rollbackTransaction(conn); 37 throw new RuntimeException(); 38 }finally { 39 DbUtil.close(rs); 40 DbUtil.close(pstmt); 41 DbUtil.resetConnection(conn); //重置Connection的状态 42 DbUtil.close(conn); 43 } 44 return value; 45 }
总结:不断提高自己编程效率!