前一篇處理過依賴項目pom.xml
,撰寫一個controller
,透過畫面拿到學生資訊,還沒真正實作從資料庫存取資料。
在使用JPA
前,這次用使用JDBC Template
做簡單的存取,既不用很原始的手動處理JDBC
細節,也不會受制於ORM
框架下的程式寫法。
pom.xml
中,以及application.yaml
內有處理資料庫連線設定<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
要做的流程如下:
endpoint
為觸發點,在頁面請求後,跟資料庫要資料table_configs
表中,拿到對應資料表要執行的SQL查詢heavy_records
表為例table_configs
heavy_records
heavy_records
資料表是為了模擬表中記錄達一定量級下,確認運行過程中會不會出現記憶體不足或效能不佳等問題出現,暫時先塞入10000筆無意義的假數據進行測試。
撰寫DataFetchService
用來取資料:
@Service
成為一個component
讓Spring
知道是一個要列入控管的Bean
。@Autowired
在建立這個物件時注入JDBCTemplate
fetch_size
,先用queryForList
測試看看@Service
public class DataFetchService {
@Autowired
private JdbcTemplate template;
public List<Map<String, Object>> getAllData(String sql) {
var result = template.queryForList(sql);
return result;
}
}
借一下原本的StudentController
中進行本次的邏輯實作:
DataFetchService
service
查詢資料庫,並且確保設定的表在要輸出的清單中,清單為後續規劃使用csv
檔案@Autowired
DataFetchService service;
@GetMapping("/student")
public Student getStudent() {
String sql = "select * from table_configs";
var configs = service.getAllData(sql);
var targetTables = List.of("heavy_records");
for (var config : configs) {
String tableName = config.get("table_name").toString();
if (targetTables.contains(tableName)) {
System.out.println("settings: " + configs.get(0));
}
}
var executeSql = configs.get(0).getOrDefault("execute_sql", "").toString();
System.out.println("actual query sql : " + executeSql);
var resultList = service.getAllData(executeSql);
System.out.println("chack data: " + resultList.get(0));
String exportFileName = "test.csv";
CsvUtils.writeMapToCSV(resultList, getHeaders(), exportFileName, '|');
return new Student(1, "John");
}
log確認資料
從log中可以看到,如預期中資料庫中獲取設定內資訊,並成功獲取對應表的資料。
輸出的csv檔案
最後將資料輸出檔案,確認10000
筆寫入。
因為重複操作,且輸出寫檔的程式寫成增加的模式,才會看到快4萬筆紀錄。
雖然加入了不少東西,實際跟資料庫交換只要依賴跟連線配置處理完成,就可以透過JDBC Template
進行存取了。
其他需求端看業務流程進行處理,例如資料格式轉換、客製分隔符號、語法檢核、異常處理、定期排程觸發、寄送通知信等機制,都可以有彈性的追加微調。