This post describes a simple setup of a web application. It has a web front (JSF), a backing bean (CDI), a database entity (JPA) and a Java Bean (EJB) for database access.
Find the whole example on GitHub: https://github.com/sapsiero/webapp-demo2
Setting up a JPA Entity
First set up a JPA entity by simply adding the @Entity annotation. A JPA entity always needs an identifier (in this case the id). This field has to be marked with the @Id annotation. Using the @GeneratedValue(strategy = GenerationType.AUTO) makes sure that the Id is generated by the JPA framework.
@Entity
public class PersonEntity {
long id;
String name;
String firstName;
int age;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
...
Setting up an Enterprise Java Bean (EJB)
The EJB is responsible for persisting the entity object into a persistence contect. The EJB container offers transcations and dependency injection, so that the configuration can easily be made.
The EJB is stateless (@Stateless), since it has no need for state information. The entity manager is automatically injected using the @PersistenceContext annotation.
@Stateless
public class PersonBean {
@PersistenceContext
EntityManager em;
public List list() {
TypedQuery q = em.createQuery("Select p From PersonEntity p", PersonEntity.class);
return q.getResultList();
}
...
Setting up the backing CDI bean
The backing bean is a request scoped CDI bean. To make a POJO available in JSF Faceletts you have to name it (@Named). Furthermore the @RequestScoped annotation determines that the objects’ lifecycle is related to the users request.
Two objects are injected into this class: The personEntity is an instance of the just created JPA class PersonEntity. The personBean is an instance of the stateless EJB.
@Named
@RequestScoped
public class PersonController {
@Inject
PersonEntity personEntity;
@Inject
PersonBean personBean;
public List getListAll() {
return personBean.list();
}
public String save() {
personBean.save(personEntity);
return "index";
}
...
Adding the Faceletts
In this example you only need to faceletts: one showing the list of PersonEntity objects (name it index.xhtml) and another making the data available in an HTML formular (edit.xhtml).
<h:body>
<h:outputLabel value="Existing persons"/>
<h:dataTable value="#{personController.listAll}" var="person">
<h:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<h:form>
<h:commandButton value="Edit" action="#{personController.edit(person.id)}"/>
</h:form>
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel value="Del"/>
</f:facet>
<h:form>
<h:commandButton value="Del" action="#{personController.delete(person.id)}"/>
</h:form>
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel value="First Name"/>
</f:facet>
<h:outputLabel value="#{person.firstName}" />
</h:column>
...


