JBoss recipe of the day

You can use the createNativeQuery method of the EntityManager interface to create a
dynamic query using SQL as follows:

 

Query q = em.createNativeQuery("SELECT p1.last_name, t1.title_name, t2.title_name
FROM person p1 INNER JOIN title t1 ON p1.title_1 = t1.title_abbrev,
     person p2 INNER JOIN title t2 ON p2.title_2 = t2.title_abbrev",
sample.Person.User.class);
return q.getResultList();


here we pass two parameters to the method createNativeQuery: the first is the SQL and
the second is the Entity which will be populated.


What about if your query returns more than one Entity ? You have to use the @SqlResultSetMapping
which will be passed to the method instead of the Entity:

At first we define the mapping:

@SqlResultSetMapping(name = "MyMapping",
entities = @EntityResult(entityClass = sample.Person.User.class))

then we can specify the mapping in the Query as follows:

Query q = em.createNativeQuery("SELECT p1.last_name, t1.title_name, t2.title_name
FROM person p1 INNER JOIN title t1 ON p1.title_1 = t1.title_abbrev,
     person p2 INNER JOIN title t2 ON p2.title_2 = t2.title_abbrev",
sample.Person.User.class);
return q.getResultList();
0
0
0
s2smodern