JPA native query return class

后端 未结 4 794
别跟我提以往
别跟我提以往 2021-02-06 06:32

In the JPA, I defined a native sql which will return String,

@NamedNativeQuery(name = \"alert\", 
query = \" select distinct c.accountId from account c \", 
            


        
相关标签:
4条回答
  • 2021-02-06 06:52

    Do not include resultClass in query declaration

    0 讨论(0)
  • 2021-02-06 06:54

    Seems Hibernate only allows Entity result classes. Obviously not all JPA implementations have this restriction. DataNucleus JPA, for example, allows that query to run fine.

    0 讨论(0)
  • 2021-02-06 06:56
    @SqlResultSetMappings({
        @SqlResultSetMapping(name = "alertMapping", columns = {
            @ColumnResult(name = "accountId")})
    })
    @NamedNativeQuery(name = "alert", 
    query = " select distinct c.accountId from account c ", 
            resultSetMapping = "alertMapping")
    

    Usage:

    EntityManager em = ...... / injected / etc
    TypedQuery<String> query = em.createNamedQuery("alert", String.class);
    List<String> accountIds = query.getResultList();
    

    (unchecked syntax, but I hope the basic idea comes through)

    For NamedNativeQueries you can only use resultClass when the result actually maps to an Entity. It's also possible to not specify a result mapping, in which case you'd get a List of Object[] back. Each element of the list would be one record, and you'd have to explicitly cast each Object to the type you wanted. Hm, the last part might only be available to NativeQueries and not Named - sorry unsure at the moment.

    0 讨论(0)
  • 2021-02-06 07:01

    In my case, I changed hibernate version from 3.5.6 to 4.3.3. it is working fine.

    <!--     <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>3.5.6-Final</version>
            </dependency>
    
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>3.5.6-Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-annotations</artifactId>
                <version>3.5.6-Final</version>
            </dependency> -->
    
    
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.3.3.Final</version>
            </dependency>
            <dependency>
              <groupId>org.hibernate</groupId>
              <artifactId>hibernate-core</artifactId>
              <version>4.3.3.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>4.3.3.Final</version>
            </dependency>
    
    0 讨论(0)
提交回复
热议问题