Meaningless Drivel is fun!
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes JNDI look for EntityManager Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "JNDI look for EntityManager" Watch "JNDI look for EntityManager" New topic

JNDI look for EntityManager

Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 850
Is it possible to JNDI lookup for EntityManager? How?

In ejb 3 in action, page-432,

return (EntityManager)ctx.lookup(EM_NAME);

but in my code also i am doing like this-\
package Factory;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.sql.DataSource;

import Pack.Car;

public class CarEAOImpl implements CarEAO{

public CarEAOImpl(){


private EntityManager getEntityManager() throws NamingException{
InitialContext ctx = null;
ctx = new InitialContext();

catch(Exception e){

return (EntityManager)ctx.lookup("jdbc/ActionBazaarDS");
public void addCar(String steering, String horn, String wheel) {
EntityManager em;
try {
em = getEntityManager();
Car c = new Car(steering, horn, wheel);

} catch (NamingException e) {
// TODO Auto-generated catch block


when it is doing lookup for DataSource, it is giving exception. As the returned value is DataSource and it cannot cast to EntityManager.

But how it was done in book.

Moreover, in Glassfish, we can set only JDBC datasources only, is it possible to set EntityManager also, so that directly i can look for it.

SCJP 1.4, SCWCD 5, SCBCD 5, OCPJWSD 5,SCEA-1, Started Assignment Part 2
My blog-
jeff mutonho
Ranch Hand

Joined: Apr 30, 2003
Posts: 271
Hi Amandeep
Look at the example at Sahoo's blog.He talks about 2 approaches on how to use JNDI lookup to get your EM.
The article is at Sahoo's Blog

If you're lazy to read the whole article , just look under the sub-heading "Container Managed Entity Manager"
I agree. Here's the link:
subject: JNDI look for EntityManager
jQuery in Action, 3rd edition