I'm using Wildfly 8.2, JavaEE 7 and Vaadin 7. I got NullPointerException when calling the stateless bean findAll() method in the user interface layer. Do you know why? Below are my code.
@MappedSuperclass
public abstract class AbstractEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//Getters/Setters are here
}
@Entity
public class Patient extends AbstractEntity {
String firstName;
String lastName;
Date DOB;
public Patient() {}
//Getters/Setters are here
}
@Stateless
public class PatientService {
@PersistenceContext(unitName="patient-pu")
private EntityManager em;
public List<Patient> findAll() {
CriteriaQuery<Patient> cq = em.getCriteriaBuilder().createQuery(Patient.class);
cq.select(cq.from(Patient.class));
return em.createQuery(cq).getResultList();
}
}
Here's my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="patient-pu" transaction-type="JTA">
<jta-data-source>java:jboss/h2</jta-data-source>
<class>com.example.samples.backend.data.Patient</class>
</persistence-unit>
</persistence>
Here's my Vaadin UI.
@Viewport("user-scalable=no,initial-scale=1.0")
@Theme("valo")
@Widgetset("com.example.MyAppWidgetset")
public class MyUI extends UI {
@Inject
private PatientService patientService;
@Override
protected void init(VaadinRequest vaadinRequest) {
patientService.findAll();
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
You get a NPE
because patientService
is null
.
The problem is that the MyUI
class is not a managed bean, meaning that it's not created by the Java EE container and that's why the @Inject
annotation don't have any effect.
The easiest way to make MyUI
as a managed bean, is to use the Vaadin CDI addon.