Home JBoss howto Web applications How to use JPA from a JBoss Web application ?
12 | 03 | 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
Login
Sign here for the NewsLetter.



Poll
What book could be in your wish list next XMas ?
 
JBoss admin resources
Banner
JBoss howto

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 do I configure a Queue/Topic to work in a cluster?

JBoss recipe of the day ...
Read More
How to use JPA from a JBoss Web application ?
Written by F.Marchioni   

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();
		}
						 
	}

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."