带有SqlResultMapping的JPA NamedNativeQuery

时间:2017-11-16 20:04:51

标签: hibernate jpa entitymanager

我的原生查询有问题。我有以下实体:

    @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

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

1 个答案:

答案 0 :(得分:0)

问题是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);