hibernate - 使用 hibernate @NamedNativeQuery 返回数值

标签 hibernate jpa

我有这个问题:

“...如果查询只返回一个数字(即,查询类似于‘select count(id) where.....)我遇到了这个错误

org.hibernate.cfg.NotYetImplementedException:尚不支持纯 native 标量查询”

更多详情请见:http://atechnicaljourney.wordpress.com/2012/09/30/hibernate-pure-native-scalar-queries-are-not-yet-supported/

我不想有一个包装类,尤其是不想有一些额外的表。这样做的正确方法是什么?

最佳答案

面临“尚不支持纯 native 标量查询”。我需要运行以查询名称作为参数的计数查询,并且其中一个查询必须是 native SQL。
能够通过创建虚假实体来克服:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * Simple wrapper entity work around for the limited hibernate pure native query
 * support. Where an HQL query is not possible
 */
@SuppressWarnings("serial")
@Entity
public class CountDTO  extends Number {

    @Id
    @Column(name = "COUNT")
    private Long count;

    @Override
    public double doubleValue() {
        return count.doubleValue();
    }

    @Override
    public float floatValue() {
        return count.floatValue();
    }

    @Override
    public int intValue() {
        return count.intValue();
    }

    @Override
    public long longValue() {
        return count.longValue();
    }

}

然后我设置 resultClass = CountDTO.class
@NamedNativeQueries({
    @NamedNativeQuery (name="postIdSecurity",
            query="select count(...) ...", resultClass = CountDTO.class)
})

并得到计数:
    ((Number) getEntityManager().createNamedQuery(qryName).
setParameter(...).getSingleResult()).longValue()

积分转至:http://jdevelopment.nl/hibernates-pure-native-scalar-queries-supported/#comment-1533

关于hibernate - 使用 hibernate @NamedNativeQuery 返回数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13278544/

相关文章:

java - 一对多 : java. sql.SQLSyntaxErrorException:表 'table_name' 不存在

java - 反序列化 JAX-RS JSON 对象时解析 JPA 关联

java - JPA 在 2 个不同模式和 session 之间复制项目

java - 存储对象时出现 ConstraintViolationException 1 :n relationship

java - jpa select 无法工作

hibernate - 任何有关 `saveAll`的文档?

java - 在 Hibernate 中延迟初始化集合

java - 将表映射到 Hibernate 中的两个继承表

mysql - SQL JPA 原生查询

java - hibernate 连接tomcat