persistence@glassfish.java.net

Setting the EntityManagerFactory from a configuration file

From: Decker, Paula \(EOIR\) <"Decker,>
Date: Fri, 13 Feb 2009 08:01:20 -0500

Hello,

 

            I am trying to set the EntityManager from within a
servlet-based web service by reading from a configuration file. Will
the code shown below work? I am using entity beans and Toplink JPA for
persistence on Glassfish. Will the code below override any information
in the sun-resources.xml file or the persistence.xml file? Before
writing the code below, I was calling: EntityManager em =
(EntityManager) ctx.lookup("persistence/LogicalName"); each time I
wanted to persist a row. What is the difference between the two ways?
After the code below executes, would I have to save an instance of the
EntityManagerFactory to use for the next row persistence? Or is there a
short cut to getting the EntityManagerFactory which was created with the
HashMap (code below)? Thanks so much for any help you can give.

 

            MessageContext mc = wsContext.getMessageContext();

            ServletContext context =

                    ((javax.servlet.ServletContext)

                    mc.get(MessageContext.SERVLET_CONTEXT));

            String filename = context.getInitParameter("config_file");

 

            InputStream is =

                    this.getClass().getResourceAsStream(filename);


            Properties props = new Properties();

            props.load(is);

            

            Map map = new HashMap();

 
map.put("toplink.jdbc.driver",props.getProperty("config.jdbc.driver"));

 
map.put("toplink.jdbc.url",props.getProperty("config.jdbc.url"));

 
map.put("toplink.jdbc.password",props.getProperty("config.jdbc.password"
));

 
map.put("toplink.jdbc.user",props.getProperty("config.jdbc.user"));

            EntityManagerFactory emf =

                    Persistence.createEntityManagerFactory("PUName",
map);

            EntityManager em = emf.createEntityManager();