Returning a numeric value with hibernate @NamedNativeQuery

前端 未结 3 2032
挽巷
挽巷 2021-01-06 11:57

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

相关标签:
3条回答
  • 2021-01-06 12:14

    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

    0 讨论(0)
  • 2021-01-06 12:29

    You can actually do this the following way:

    @NamedNativeQueries({
            @NamedNativeQuery(
                    name = "countAll",
                    query = "select count(*) from MyTable"
            )
    })
    public class MyTable ...
    
    
    // execute like this:
    ((BigInteger) manager.createNamedQuery("countAll").getSingleResult()).intValue();
    
    0 讨论(0)
  • 2021-01-06 12:32

    I did a work around using createQuery() instead: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html#objectstate-querying

    0 讨论(0)
提交回复
热议问题