I am writing my first Java EE application (EJB + Servlets, etc.) (note: I am using Eclipse).
I ran into a problem when the EntityManager injection did not work, and with some difficulties I found out why because of my Java EE (and Java in general) noobness.
Here is my file persistence.xml- I think this is mostly correct, since I can start the HSQL database manager from the JMX console and my PUBLIC.USER table will appear correctly.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="MyPu">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
Here is my servlet code:
[...]
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
String id = request.getParameter("username");
String password = request.getParameter("password");
UserManagerBean um = new UserManagerBean();
um.register(username, password);
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
And here is my UserManagerBean class:
import myPackage.UserManager;
public @Stateful class UserManagerBean implements UserManager {
@PersistenceContext(unitName="MyPu")
private EntityManager persistManager;
public void register(String username, String password) {
User user = new User(userame, password);
persistManager.persist(user);
persistManager.flush();
}
}
persistManager.persist(user) NullPointerException.
, , , new() UserManagerBean, @PersistenceContext , persistManager .
, , - EJB.
bean? ? , bean :\
:
,
UserManagerBean um = new UserManagerBean();
@EJB
private UserManagerBean um;
. um - NullPointer.