資料表無「集合」類型,Java List<String> 必須映射為關係模型。
// 寫入
String joined = String.join(";", stringList); // "A;B;C"
jdbc.update("INSERT INTO t(col) VALUES (?)", joined);
// 讀取
List<String> list = Arrays.asList(row.getString("col").split(";"));
CREATE TABLE parent (id PK, ...);
CREATE TABLE child_strings (parent_id FK, idx INT, val VARCHAR(255), PK(parent_id, idx));
// 批次寫入
List<BatchPreparedStatementSetter> batch = list.stream()
.map(v -> new AbstractBatchPreparedStatementSetter() { ... })
.collect(toList());
jdbc.batchUpdate("INSERT INTO child_strings VALUES (?,?,?)", batch);
| 場景 | 推薦 |
|---|---|
| 標籤、枚舉值、不須檢索 | 方案一 (JSON 也可) |
| 需按元素查詢/統計/關聯 | 方案二 |
| 元素為複雜物件 | 方案二 + 物件表 |
@ElementCollection + @CollectionTable 自動映射方案二。<collection> 映射關聯表,或 TypeHandler 處理方案一。