【问题标题】:JPA NamedNativeQuery with SqlResultMapping带有 SqlResultMapping 的 JPA NamedNativeQuery
【发布时间】:2017-11-16 20:04:50
【问题描述】:

我对本机查询有疑问。我有以下实体:

    @Entity
@NamedNativeQueries({
    @NamedNativeQuery(name =  ExampleEntity.Q.getTestQuery, query = "SELECT a.name as name FROM ExampleEntity a WHERE a.id = 5", resultSetMapping = "nameMapping")
})

@SqlResultSetMapping(
    name = "nameMapping",
    entities = @EntityResult(
        entityClass = ExampleEntity.class,
        fields = {
            @FieldResult(name="name", column="name")
        }))


@Table(name = "ExampleEntity")
public class ExampleEntity implements Serializable {

    public static class Q {
        public static final String getTestQuery = "getTestQuery";
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;

我正在尝试使用以下代码在我的@Service 中调用此查询:

Query qz = em.createNativeQuery(ExampleEntity.Q.getTestQuery, "nameMapping");
qz.getResultList();

返回错误:

org.hibernate.exception.SQLGrammarException: could not extract ResultSet

这只是一个简单的例子,但显示了我的问题。 非常感谢!

【问题讨论】:

  • 请添加完整的堆栈跟踪。
  • service.test() 中的异常,原因 = 'org.hibernate.exception.SQLGrammarException: could not extract ResultSet' and exception = 'org.hibernate.exception.SQLGrammarException: could not extract ResultSet' javax .persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: 无法提取结果集

标签: hibernate jpa entitymanager


【解决方案1】:

问题在于createNativeQuery 方法期望 SQL 查询字符串作为第一个参数,而不是用于引用 SQL 查询本身的名称。这是方法定义:

public Query createNativeQuery(String sqlString, String 结果集映射);

这将我们带到以下内容:

Query qz = em.createNativeQuery("SELECT a.id, a.name FROM ExampleEntity a WHERE a.id = 5", 
                                "nameMapping");

首选的解决方案是使用createNamedQuery,而不是使用元数据中定义的 SQL 查询的名称:

public Query createNamedQuery(字符串名称);

所以基于上述我们可以通过以下方式修复异常:

Query qz = em.createNamedQuery(ExampleEntity.Q.getTestQuery);

【讨论】:

  • 我试图以这种方式解决问题,但我收到:org.postgresql.util.PSQLException:在此结果集中找不到列名 id1_7_0_。但我没有这样的专栏......
  • PSQL 异常与 id 列有关。将@FieldResult(name="id", column="id") 添加到字段映射并更新查询,例如SELECT a.id, a.name FROM ExampleEntity a WHERE a.id = 5
猜你喜欢
  • 1970-01-01
  • 2013-09-16
  • 2015-09-01
  • 2017-12-25
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多