【问题标题】:Unable to run native JPA queries in testEntityManager container无法在 testEntityManager 容器中运行本机 JPA 查询
【发布时间】:2014-09-19 04:02:07
【问题描述】:

注意:我在 eclipse 论坛上发布了这个问题,但没有收到回复,尽管我认为我对问题的描述已经足够清楚了。

我把它贴在这里。如果有人可以提供帮助,那就太好了。

我有一个 JPA 实体类,它在数据库中没有支持它的表。我们只是创建了它,因为我们必须运行一个查询,该查询需要对许多表执行连接。因此,我们没有创建命名查询,而是采用原生查询方式来提高速度。那就是我们有一个 JPA 实体,例如:

@Entity

@SqlResultSetMapping(name = "userMapping", entities=@EntityResult(entityClass =  
User.class))

@NamednativeQuery(name = "User.query", query = "-- native query here --",   
resultSetMapping = "userMapping")

public class User {

}

现在可以使用 entityManager 对象正常运行,例如: em.createNamedQuery("User.query").setParameter("userParam", param).getResultList();

但是,在 entitymanager 容器环境(使用 EntityManagerFactory 创建)中使用 Testng 进行测试时,会抛出 0RA-942 表或视图不存在错误。我们尝试在persistence.properties 和SessionCustomizer 中启用use_native_sql = true。

我们使用 eclipselink JPA。

有人可以对此提供一些反馈吗?

谢谢

【问题讨论】:

  • 您是否在容器与 JSE 环境中针对同一个数据库进行测试?
  • 是的。我在 EntityManager(persistence-unit-name, persistence.properties); 中设置了持久性属性。我为此测试定制了数据库会话,并在其中设置了要使用的架构。

标签: jpa eclipselink testng nativequery


【解决方案1】:

解决您的问题的线索可能是您的本机查询的结构。

我使用 Eclipselink 2.5.1 测试了使用未映射实体和 Named Native 查询的简单用例,效果很好。我使用的代码是这样的(表 EMPLOYEE 存在于底层数据库中,表 USER 不存在)。

@Entity
public class Employee {
    @Id @GeneratedValue int id;
}

@Entity
@SqlResultSetMapping(name="userMapping", entities=@EntityResult(entityClass=User.class))
@NamedNativeQuery(name="User.query", query="SELECT id FROM \"User\"", resultSetMapping =      "userMapping")
public class User {
    @Id
    @GeneratedValue
    int id;
}

使用此代码命名的查询成功执行并产生与 EMPLOYEE 表中一样多的结果。但是,如果我以某种方式将本机查询更改为使用 USER 表,我会得到 ​​p>

SQLSyntaxErrorException: Table/View 'User' does not exist.

您可能正在使用您正在使用的命名查询来更新您的问题,并且报告了哪个表不存在以确认是这种情况。

【讨论】:

  • 感谢您的意见。显然,解决方案似乎是在运行查询之前,我必须运行“ALTER SESSION SET CURRENT_SCHEMA="schema"。虽然我使用 .setTableQualifier("schema") 为整个会话设置了架构。它似乎没有被本机查询提取?
猜你喜欢
  • 2015-02-21
  • 2011-03-09
  • 1970-01-01
  • 2021-06-04
  • 2017-08-11
  • 1970-01-01
  • 2016-11-02
  • 2012-10-09
  • 2019-06-21
相关资源
最近更新 更多