Home >Java >javaTutorial >How to Convert Native Query Results to POJOs in JPA?

How to Convert Native Query Results to POJOs in JPA?

DDD
DDDOriginal
2024-12-11 21:36:12802browse

How to Convert Native Query Results to POJOs in JPA?

JPA: Converting Native Query Results to POJO Classes

Problem:

In JPA, when executing a native query, the result is typically returned as an object array or a list of arrays. Is there a way to directly convert this result to a collection of Java POJO (Plain Old Java Objects) classes that have the same column names as the result set?

Solutions:

Using Mapped Entities (JPA 2.0 and above)

JPA 2.0 onwards allows mapping native query results to POJOs that are mapped entities in the persistence context. To achieve this, annotate the POJO class with @Entity and use a named native query with resultClass set to the POJO class:

@NamedNativeQuery(
    name = "nativeSQL",
    query = "SELECT * FROM Actors",
    resultClass = Actor.class
)

Manual Mapping

For cases where using mapped entities is not feasible, manual mapping can be used. This involves creating a method that takes an array of objects (the tuple) as input and maps it to a POJO using reflection:

public static <T> T map(Class<T> type, Object[] tuple) {
    // ... (Reflection code omitted for brevity)
}

Using @SqlResultSetMapping (JPA 2.1 and above)

JPA 2.1 introduces the @SqlResultSetMapping annotation, which allows custom mapping of native query results to POJOs. Define a mapping in an entity or orm.xml file and use it in the native query:

@SqlResultSetMapping(
    name = "JediResult",
    classes = {
        @ConstructorResult(
            targetClass = Jedi.class,
            columns = {
                @ColumnResult(name = "name"),
                @ColumnResult(name = "age")
            }
        )
    }
)
Query query = em.createNativeQuery("SELECT name,age FROM jedis_table", "JediResult");

Using XML Mapping

Instead of using annotations, custom result set mapping can be defined in the orm.xml file, allowing for a more centralized configuration.

<sql-result-set-mapping name="JediMapping">
    <constructor-result target-class="org.answer.model.Jedi">
        <column name="name" class="java.lang.String"/>
        <column name="age" class="java.lang.Integer"/>
    </constructor-result>
</sql-result-set-mapping>

The above is the detailed content of How to Convert Native Query Results to POJOs in JPA?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn