Struts B/S 系統的資料字典表結構 table(id, name),ID 格式為 A01、A02、B10、C12... 每字典分配一字母前綴,便於除錯識別。新增時需自動生成連續 ID(含補齊刪除產生的間隙)。
X01(X 為前綴)。01~99),組合新 ID。public String generateNextId(String prefix, Connection conn) throws SQLException {
// 1. 查詢該前綴所有 ID
String sql = "SELECT id FROM dict_table WHERE id LIKE ? ORDER BY id";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, prefix + "%");
ResultSet rs = ps.executeQuery();
// 2. 收集現有數字後綴
Set used = new TreeSet<>();
while (rs.next()) {
String id = rs.getString("id");
if (id.length() == 3) { // 前綴1碼 + 2位數
try {
int num = Integer.parseInt(id.substring(1));
used.add(num);
} catch (NumberFormatException ignored) {}
}
}
// 3. 找最小缺失正整數 (1~99)
int next = 1;
for (int n : used) {
if (n == next) next++;
else if (n > next) break; // 找到間隙
}
if (next > 99) throw new IllegalStateException("ID 耗盡 (超過 99)");
// 4. 格式化
return prefix + String.format("%02d", next);
}
}
ORDER BY id 排序正確(A1 會排在 A10 之前)。A02 後,新增優先補 A02 而非 A04。資料字典項目 ≤ 100、單字母前綴、需連續編號且重用間隙的輕量級場景。大規模或高併發環境請使用資料庫序列或分散式 ID 生成器。