How to use JPA from a JBoss Web application ?(jboss 中如何使用线程安全的EntityManagerFactory )

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 yourpersistence.xml file:

01. <persistence
02.  
03. <persistence-unit name="unit1">
04. <provider>org.hibernate.ejb.HibernatePersistence</provider>
05. <jta-data-source>java:/MySqlDS</jta-data-source>
06. <properties>
07. <property name="hibernate.dialect"
08. value="org.hibernate.dialect.MySQLDialect"/>
09. <propertyname="jboss.entity.manager.factory.jndi.name"value="java:/MyEntityManagerFactory"/>
10. </properties>
11.  
12. </persistence-unit>
13.  
14. </persistence>

Then from your web application:

01. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
02. InitialContext ctx;
03. try {
04. ctx = new InitialContext();
05. EntityManagerFactory factory = (EntityManagerFactory)ctx.lookup("java:/MyEntityManagerFactory");
06.  
07. System.out.println("Factory is "+factory);
08. catch (NamingException e) {
09. // TODO Auto-generated catch block
10. e.printStackTrace();
11. }
12.  
13. }

你可能感兴趣的:(How to use JPA from a JBoss Web application ?(jboss 中如何使用线程安全的EntityManagerFactory ))