使用hibernate @NamedNativeQuery返回数值

Pet*_*erg 2 hibernate jpa

我有这个问题:

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

org.hibernate.cfg.NotYetImplementedException:尚不支持纯本机标量查询 "

有关详细信息,请参阅:http://atechnicaljourney.wordpress.com/2012/09/30/hibernate-pure-native-scalar-queries-are-not-yet-supported/

我不想有一个包装类,特别是没有一些额外的表.这样做的正确方法是什么?

Vol*_*ach 6

面临"尚未支持纯本机标量查询".我需要运行具有查询名称作为参数的计数查询,其中一个查询必须是本机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();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后我就设定了 resultClass = CountDTO.class

@NamedNativeQueries({
    @NamedNativeQuery (name="postIdSecurity",
            query="select count(...) ...", resultClass = CountDTO.class)
})
Run Code Online (Sandbox Code Playgroud)

得到数:

    ((Number) getEntityManager().createNamedQuery(qryName).
setParameter(...).getSingleResult()).longValue()
Run Code Online (Sandbox Code Playgroud)

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