我正在将一个项目从Hibernate 4.2.6迁移到5.2.0。
我注意到对于Hibernate 5.2.0,本地查询现在需要零基础的参数定位。
根据JPA 2.1规范:
根据 Hibernate 文档 Query.setParameter(int, Object),位置编号从 0 开始。Hibernate 4.2 和 5.2 文档中都有说明。
我进行了微型测试。
首先使用 Hibernate 4.2.6。
这适用于Hibernate 4.2.6。
持久化配置文件(persistence.xml)如下所示。
唯一的区别在于 setParameter 中的 0 索引。 persistence.xml 也非常相似。
我在两个版本中追踪了代码。我能够在4.2.6中找到处理基于1的索引的代码,但在5.2版本中找不到类似的代码。
我在Hibernate forums 中发现了一篇2009年的帖子:
只有当您使用JPA-Query-Api时,第一个参数必须具有索引= 1。您正在使用Hibernate-Query-Api,其中第一个参数必须具有索引= 0。
显然我在使用JPA。所以问题是:
是否有一种方法可以配置Hibernate 5.2以获取基于1的位置参数?我不想更改代码以符合规范。
我注意到对于Hibernate 5.2.0,本地查询现在需要零基础的参数定位。
根据JPA 2.1规范:
我对规范的理解是,即使对于本地查询,编号也应该从1开始。3.10.13位置参数
对于本地查询,除了已定义命名参数的存储过程查询外,只能使用位置参数绑定和位置访问结果项。 当绑定位置参数的值时,编号从“1”开始。 假定对于本地查询,参数本身使用SQL语法(即“?”而不是“?1”)。
根据 Hibernate 文档 Query.setParameter(int, Object),位置编号从 0 开始。Hibernate 4.2 和 5.2 文档中都有说明。
我进行了微型测试。
首先使用 Hibernate 4.2.6。
@PersistenceContext
private EntityManager entityManager;
Query query = entityManager.createNativeQuery("select * from Game g where title = ?");
query.setParameter(1, GAME_TITLES[0]);
List list = query.getResultList();
这适用于Hibernate 4.2.6。
持久化配置文件(persistence.xml)如下所示。
<persistence-unit name="test" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/arquillian</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
与Hibernate 5.2相同
Query query = entityManager.createNativeQuery("select * from Game g where title = ?");
query.setParameter(0, GAME_TITLES[0]);
List list = query.getResultList();
唯一的区别在于 setParameter 中的 0 索引。 persistence.xml 也非常相似。
<persistence-unit name="test">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/arquillian</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
我在两个版本中追踪了代码。我能够在4.2.6中找到处理基于1的索引的代码,但在5.2版本中找不到类似的代码。
我在Hibernate forums 中发现了一篇2009年的帖子:
只有当您使用JPA-Query-Api时,第一个参数必须具有索引= 1。您正在使用Hibernate-Query-Api,其中第一个参数必须具有索引= 0。
显然我在使用JPA。所以问题是:
是否有一种方法可以配置Hibernate 5.2以获取基于1的位置参数?我不想更改代码以符合规范。