JPA NamedNativeQuery 与 SqlResultMapping

JPA NamedNativeQuery with SqlResultMapping

我的本机查询有问题。我有以下实体:

    @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();

它returns错误:

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

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

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

public Query createNativeQuery(String sqlString, String resultSetMapping);

这给我们带来了以下内容:

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

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

public Query createNamedQuery(String name);

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

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