在某些大企業(yè)里,Oracle的account角色是分得很清楚的。
- Schema account: 用于管理整個(gè)schema
- Application account: 用來給應(yīng)用程序使用
- Read only account: 只讀用戶,用來做交互式查詢
...
雖然分配數(shù)據(jù)庫的時(shí)候,是以Schema Account來做Schema的,但是每個(gè)Account,其實(shí)也有它自己的Schema 空間。那么問題來了,應(yīng)用程序需要用到的表,在schema account的schema里面,那么當(dāng)程序用application account去連接的時(shí)候,就會發(fā)現(xiàn)找不到Table,因?yàn)锳pplication account的默認(rèn)Schema是它自己。于是,很多人的慣例,是創(chuàng)建同義詞synonym,那么訪問的時(shí)候就沒有障礙了。可是其實(shí)Synonym的創(chuàng)建其實(shí)是挺困難的。為什么呢?因?yàn)镾chema Account沒權(quán)限給Application Account創(chuàng)建Synonym,Application Account一般沒權(quán)限給自己創(chuàng)建,于是乎,又要去麻煩DBA然后被各種鄙視…
言歸正傳,Java,尤其是Hibernate,JPA這些,是支持設(shè)置Schema的,也許在多數(shù)據(jù)源的情況下,可能遇到一些問題,但是現(xiàn)在是微服務(wù)年代,誰特么還配置雙數(shù)據(jù)源?趕緊重構(gòu)??!
以Spring boot為例,這樣配就對了
spring.jpa.properties.hibernate.default_schema=my_schema
如果用到NativeQuery, 可以這樣搞
@Query("select * from {h-schema}user", nativeQuery=true)
這個(gè) {h-schema}占位符,是Hibernate的語法。
有興趣的看一下英文資料:
Working with a default schema is so much easier when the schema name is defined only one, by the hibernate.default_schema configuration property. While this works just fine for JPQL queries, for native queries you need to provide the {h-schema} placeholder.
Hibernate also defines h-domain and h-catalog placeholders as well. The {h-catalog} resolve the global catalog defined by the hibernate.default_catalog configuration property. The {h-domain} resolves both the global catalog and schema, injecting them like this: catalog.schema.