Java Reference
In-Depth Information
This is useful when the SQL query returns more than one entity. The persistence provider
will automatically determine the entities being returned based on the SqlRes-
ultSetMapping , instantiate the appropriate entities, and initialize those entities with
values based on the O/R mapping metadata.
Once you create a query, it makes no difference whether you retrieve the results from a nat-
ive SQL or a JPQL query.
11.3.2. Using a named native SQL query
Using a named native query is quite similar to using a named JPQL query. To use a named
native query, you must first create it. You can use the @NamedNativeQuery annotation
to define a named query:
public @interface NamedNativeQuery {
String name();
String query();
QueryHint[] hints() default {};
Class resultClass() default void.class;
String resultSetMapping() default ""; // name of SQLResultSetMapping
You can either use an entity class or a result set mapping with the @NamedNativeQuery
annotation. Suppose you want to convert the query that was used earlier to a named native
query. The first step is to define the named native query in the User entity:
name = "findUserWithMoreItems",
query = "SELECT user_id , first_name , last_name,
FROM users
WHERE user_id IN
( SELECT seller_id
FROM items
GROUP BY seller_id HAVING COUNT(*) > ?)",
hints = {@QueryHint(name = "toplink.cache-usage",
resultClass = actionbazaar.persistence.User.class)
Next, if your query returns more than one entity class, you must define SqlRes-
ultSetMapping in the entity class using resultSetMapping as follows:
Search WWH ::

Custom Search