![](/img/trans.png)
[英]How to fetch data from multiple tables in spring boot using mapping in Spring Boot's JPA repository
[英]Spring Boot JPA: Mapping one entity to multiple (a lot) tables with same columns
我有很多(比如 60 多個)具有相同架構和相似名稱的表:
log_2020_07_01
log_2020_07_02
... and so on.
它們具有相同的列: id, site, size
。 每個表包含大約 200 萬行。
我已經閱讀了 Hibernate 和具有相同數據/列但具有不同表名的表,這些表建議單獨使用 hibernate。 我希望七年后也許我們可以用 JPA 做一些新的事情。
在 JPA 中,是否可以只編寫一個實體 class 並讓代碼處理要使用的表?
例如,
for(int i=0;i<60;i++) {
// read from the i-th table.
}
首先,我們可以使用中間件使分片對中/大型項目的用戶透明。
這是我的小項目的快速解決方法(我是唯一的開發人員):
第一步,創建一個攔截器:
public class MySqlInterceptor extends EmptyInterceptor {
private String entityName;
@Setter
private int tableId;
protected MySqlInterceptor() {
super();
}
public MySqlInterceptor(String entityName) {
this.entityName = entityName;
}
@Override
public String onPrepareStatement(String sql) {
// Here is the trick.
String modifiedSql = sql.replaceAll(entityName, entityName + tableId);
log.debug("{}", modifiedSql);
return modifiedSql;
}
}
第 2 步,連接攔截器:
MySqlInterceptor mySqlInterceptor = new MySqlInterceptor("temp");
mySqlInterceptor.setTableId(tableId);
session = entityManagerFactory.unwrap(SessionFactory.class).withOptions().interceptor(mySqlInterceptor).openSession();
說明: Hibernate 正在使用 JDBC 與數據庫通信。 攔截器會在運行時將 sql 中的表名從an entity's name
(在我的例子中是 temp)更改a real table name
(temp1,temp2,...)。
PS,使用多線程時要小心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.