JBoss recipe of the day

The @PersistenceUnit and <persistence-unit-ref> elements can be used within Servlets and JSPs to access EntityManagerFactory only.

You cannot inject EntityManagers directly into web components. Unfortunately, again, Tomcat doesn't support them, so you have to lookup the EntityManagerFactory in JNDI.

To be able to do that you need to set the  jboss.entity.manager.factory.jndi.name property in your persistence.xml file:

<persistence

 <persistence-unit name="unit1">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <jta-data-source>java:/MySqlDS</jta-data-source>
    <properties>
      <property name="hibernate.dialect" 
       value="org.hibernate.dialect.MySQLDialect"/>
      <property name="jboss.entity.manager.factory.jndi.name" value="java:/MyEntityManagerFactory"/>
   </properties>
    
 </persistence-unit>
 
</persistence>

Then from your web application:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InitialContext ctx;
        try {
            ctx = new InitialContext();
            EntityManagerFactory factory = (EntityManagerFactory)ctx.lookup("java:/MyEntityManagerFactory");
            
            System.out.println("Factory is "+factory);
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                         
    }

0
0
0
s2smodern