JPA/Hibernate配置Oracle 默认schema,抛
在某些大企业里,Oracle的account角色是分得很清楚的。
- Schema account: 用于管理整个schema
- Application account: 用来给应用程序使用
- Read only account: 只读用户,用来做交互式查询
...
虽然分配数据库的时候,是以Schema Account来做Schema的,但是每个Account,其实也有它自己的Schema 空间。那么问题来了,应用程序需要用到的表,在schema account的schema里面,那么当程序用application account去连接的时候,就会发现找不到Table,因为Application account的默认Schema是它自己。于是,很多人的惯例,是创建同义词synonym,那么访问的时候就没有障碍了。可是其实Synonym的创建其实是挺困难的。为什么呢?因为Schema Account没权限给Application Account创建Synonym,Application Account一般没权限给自己创建,于是乎,又要去麻烦DBA然后被各种鄙视…
言归正传,Java,尤其是Hibernate,JPA这些,是支持设置Schema的,也许在多数据源的情况下,可能遇到一些问题,但是现在是微服务年代,谁特么还配置双数据源?赶紧重构!!
以Spring boot为例,这样配就对了
spring.jpa.properties.hibernate.default_schema=my_schema
如果用到NativeQuery, 可以这样搞
@Query("select * from {h-schema}user", nativeQuery=true)
这个 {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
.