Home JBoss howto EJB How to use native queries with EJB 3.0 ?
30 | 07 | 2010
JBoss 5 AS Book
"JBoss AS 5 development" reviews
Please share your feedback/review with other readers!
Banner
Dashboard
Advertise with Us
Banner
RSS Feed
Java EE 1.6 resources
Login
Sign here for the NewsLetter.



JBoss admin resources
Banner
Java EE 1.6 resources
JBoss howto

How to avoid the 50 seconds start up limit in Eclipse ?

JBoss recipe of the day ...
Read More

How can you solve deployment errors caused by large war/jar/ear files ?

jboss recipe of the day ...
Read More

How do you configure your .war to be deployed after your EJB ?

jboss recipe of the day ...
Read More
How to use native queries with EJB 3.0 ?
Written by F.Marchioni   

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",
"MyMapping");

 


JBoss.org Search
Custom Search
Comments
Search
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."