Alf*_*o M 9 java sql-server hibernate jpa hql
我有一个带有@Formula属性的实体,如下所示:
@Entity
@Table(name = "areasAuxiliar")
public final class AreaAuxiliar implements Serializable {
@Id
@Column(name = "idArea")
private Integer idArea;
@Formula("RUTAAREA(idArea)")
private String ruta;
Run Code Online (Sandbox Code Playgroud)
当我将我的hibernate配置为指向Oracle DB时我没有问题,但是,当我切换到SQLServer时,hibernate不包括shema并且查询失败,
为hibernate生成的查询如下所示:
select
areaauxili4_.idArea as idArea1_6_4_,
rutaArea(areaauxili4_.idArea) as formula2_4_
from
SIGAP.areasAuxiliar areaauxili4_
Run Code Online (Sandbox Code Playgroud)
param hibernate.default_schema =正在读取SIGAP并将其包含在表中但不包含在函数中,
是否有一个选项/注释来强制shema进入该函数?
我尝试过hibernate 5.1和5.2,结果相同:(
您可以使用mysql-orm.xml文件来覆盖您的公式,然后配置您的构建以在数据库为 mysql 时考虑该文件。
在这里重写公式:
<entity-mappings
xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm orm_2_1.xsd"
version="2.1">
<package>com.acme.persistence</package>
<entity class="AreaAuxiliar" access="FIELD">
<attributes>
<property name="ruta" formula="schemaName.RUTAAREA(idarea)"/>
</attributes>
</entity>
</entity-mappings>
Run Code Online (Sandbox Code Playgroud)
然后在特定的persistence.xml. 然后,您可以在构建或运行时用这个覆盖默认的 persistence.xml(参见下面的链接)。
<persistence
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<provider>
org.hibernate.jpa.HibernatePersistenceProvider
</provider>
<mapping-file>
mappings/identifier/global/mysql-orm.xml
</mapping-file>
<class>
com.acme.persistence.AreaAuxiliar
</class>
</persistence-unit>
Run Code Online (Sandbox Code Playgroud)
注意:受如何根据底层数据库更改 Hibernate GenerationType 标识符的启发很大
注意(2):在博客文章和这里,作者在运行时生成 PersistenceUnitInfo。
Alf*_*o M -1
更简化的解决方案:
改变你的@Formula:
@Formula("RUTAAREA(idArea)")
Run Code Online (Sandbox Code Playgroud)
对此:
@Formula("{MYAPP_SCHEMA}.RUTAAREA(idArea)")
Run Code Online (Sandbox Code Playgroud)
创建一个类:
public class HibernateEntityInterceptor extends EmptyInterceptor {
}
Run Code Online (Sandbox Code Playgroud)
在您的 sessionFactory 中将其注册为实体拦截器,在我的例子中:
sessionFactory.setEntityInterceptor(new HibernateEntityInterceptor());
Run Code Online (Sandbox Code Playgroud)
然后在该类中重写此方法:
public String onPrepareStatement(String sql) {
Run Code Online (Sandbox Code Playgroud)
该方法在执行之前接收 sql 命令,因此,您需要做的就是简单的全部替换:
sql = sql.replaceAll("\\{MYAPP_SCHEMA}", default_schema);
return sql;
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助。
| 归档时间: |
|
| 查看次数: |
1013 次 |
| 最近记录: |