在我的一個項目中,我有一個管理多個客戶的應用程序(或者客戶,如果您願意的話)。對於它們中的每一個,我都有一個專用的數據庫模式。但是,應用程序一次只處理一個客戶端,即用戶必須從應用程序中的一個客戶端切換到另一個客戶端(在運行時,不重新啓動應用程序)才能訪問來自此新客戶端的數據。如何用Hibernate處理幾個DB模式?
對於這類項目,您將如何管理連接以及持久層?
我想爲此使用Hibernate。處理多個數據庫/模式時,我必須非常小心的是什麼?
在這種情況下春季會有什麼幫助嗎?
如果我不夠清楚,讓我以一個例子來解釋情況。假設我的應用程序可以處理兩個客戶端:clientONE
和clientTWO
。 我已經實現了一個類,可以爲給定的客戶端提供數據庫模式,用戶,密碼和連接字符串。
每個客戶都有一個債務人清單,但不幸的是,對於clientONE
和clientTWO
,DEBTOR表結構並不相同。 即使表/列的名稱是不一樣的......
所以我可以爲每個客戶端(我使用Hibernate的註解)一個債務人類:
@Entity
@Table(name = "T_DEBTOR_ONE")
...
public class ClientOneDebtor {
@Id
@Column(name = "ID_DEBTOR")
private String idDebtor;
...
}
和:
@Entity
@Table(name = "T_DEBTOR_TWO") // Table names are not the same among the different schemas...
...
public class ClientTwoDebtor {
@Id
@Column(name = "DEBTOR_ID") // It's just to show that the same information is stored in a column that has not the same name.
private String idDebtor;
...
}
理想情況下,我會嘗試有一個共同的Debtor
類(這裏是一個抽象類,但我可以使用一個接口):
public abstract class AbstractDebtor {
public abstract String getIdDebtor();
...
}
@Entity
@Table(name = "T_DEBTOR_ONE")
...
public class ClientOneDebtor extends AbstractDebtor {
@Id
@Column(name = "ID_DEBTOR")
private String idDebtor;
...
}
@Entity
@Table(name = "T_DEBTOR_TWO")
...
public class ClientTwoDebtor extends AbstractDebtor {
@Id
@Column(name = "DEBTOR_ID") // It's just to show that the same information is stored in a column that has not the same name.
private String idDebtor;
...
}
這樣,我可以更容易地操作DAO /服務層中的Debtor對象,因爲我不需要爲每個客戶端複製我的DAO和服務。 例如,從DAO獲取所有債務人清單的方法將是public List<AbstractDebtor> getAllDebtors() { ... }
。
那麼,當我更改由我的應用程序管理的客戶端時,如何更改上下文? 換句話說,我將如何向Hibernate(或Spring?)表明我想使用正確的持久性對象(ClientOneDebtor
或ClientTwoDebtor
)來關於當前由我的應用程序管理的客戶端?
如果你認爲我在錯誤的方向我要去,不要猶豫,分享您對如何解決這類問題的想法...
關於第一答案編輯:
我需要處理的不同模式的數量在15-20左右。除此之外,我只需要映射其表格的一小部分。
我也知道每個客戶/客戶擁有一個模式並不是存儲數據的最佳解決方案。然而,這種架構自5年以來就存在了,而且我們可能在下一年只有一種模式(在最好的情況下)。)。