Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

jpa - Returning a numeric value with hibernate @NamedNativeQuery

I've this question:

"... if the query just returns a number (i.e., the query is something like ‘select count(id) where…..) I came up against this error

org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported"

For more details see: http://atechnicaljourney.wordpress.com/2012/09/30/hibernate-pure-native-scalar-queries-are-not-yet-supported/

I don't want to have a wrapper class and especially not some extra table. What is the proper way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Faced "Pure native scalar queries are not yet supported". I need to run count queries having a name of the query as parameter and one of the queries must be native SQL. Was able to overcome by creating fake entity:

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

}

Then I set resultClass = CountDTO.class

@NamedNativeQueries({
    @NamedNativeQuery (name="postIdSecurity",
            query="select count(...) ...", resultClass = CountDTO.class)
})

And get count:

    ((Number) getEntityManager().createNamedQuery(qryName).
setParameter(...).getSingleResult()).longValue()

Credits go to: http://jdevelopment.nl/hibernates-pure-native-scalar-queries-supported/#comment-1533


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...