Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Several Architectural Styles with Java EE 7

DZone's Guide to

Several Architectural Styles with Java EE 7

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

If you are like me, in your career you came across Architects who want to homogenize every single application in the company : from the smallest web app to the biggest application. All projects have to conform to the 542 pages In-house Architectural Guideand develop a 6 tier application (it could be 5, 6, 7 or 8 tiers, look like architects are paid by the tier). This is wrong. In fact, you should follow the good old saying : the right tool for the right job, or, the right architecture for the right project’s needs. And you could go even further : the right language for the right application and so on. Due to my Java EE background, I’m sticking to Java EE 7 in this post (JSF front end, EJBs services, JAX-RS endoints and JPAentities). So, how many architectural styles you can create with Java EE 7 ? An infinite ;o)

I’m writing this blog because I was showing the code generated by JBoss Forge to a colleague and he went “Forge doesn’t create a 5-tier web application“… and so what ? In this post I’ll explain the default code generated by JBoss Forge (which I call Horizontal Service Style) and the other variants you can create from it.

Horizontal Services Style

When JBoss Forge generates a JSF web application with a REST interface, both JSF backing beans and JAX-RS endpoints use the EntityManager to deal with JPA Entities. The architectural style is as follow :

Horizontal Services

I call this Horizontal Services style because if you need to add a SOAP Web Service interface, you will write aBookSOAP which will also use an EntityManager and directly invoke the entities. To have an idea of the dynamics in the code, I’ll show you an extract of some CRUD operation on both the JSF backing bean and the REST endpoint :

JSF BookBean
@Named
@Stateful
@ConversationScoped
public class BookBean implements Serializable {
// ...
@Inject
private Conversation conversation;
@PersistenceContext(unitName = "sampleJavaEEHorizontalPU", type = PersistenceContextType.EXTENDED)
private EntityManager em;
// ...
public Book findById(Long id) {
return em.find(Book.class, id);
}
public String update() {
conversation.end();
try {
if (id == null) {
em.persist(book);
return "search?faces-redirect=true";
} else {
em.merge(book);
return "view?faces-redirect=true&id=" + book.getId();
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
return null;
}
}
public String delete() {
conversation.end();
try {
Book deletableEntity = findById(getId());
em.remove(deletableEntity);
em.flush();
return "search?faces-redirect=true";
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
return null;
}
}
}

This backing bean deals with navigation (each method returns a String, which is the name of the page to navigate to) and creates, deletes, updates the Book entity. Now if you look at the REST endpoint, you will see that the responsibilities are quite similar : the BookEndpoint creates, deletes, updates the Book entity and returns aResponse. This is the code of the BookEndpoint:

JAX-RS BookEndpoint
@Transactional
@Path("/books")
public class BookEndpoint {
// ...
@PersistenceContext(unitName = "sampleJavaEEHorizontalPU")
private EntityManager em;
// ...
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/xml")
public Response findById(@PathParam("id") Long id) {
TypedQuery findByIdQuery = em.createQuery("SELECT DISTINCT b FROM Book b LEFT JOIN FETCH b.authors WHERE b.id = :entityId ORDER BY b.id", Book.class);
findByIdQuery.setParameter("entityId", id);
Book entity = findByIdQuery.getSingleResult();
if (entity == null) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok(entity).build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/xml")
public Response update(Book entity) {
em.merge(entity);
return Response.noContent().build();
}
@DELETE
@Path("/{id:[0-9][0-9]*}")
public Response deleteById(@PathParam("id") Long id) {
Book deletableEntity = em.find(Book.class, id);
if (deletableEntity == null) {
return Response.status(Status.NOT_FOUND).build();
}
em.remove(deletableEntity);
return Response.noContent().build();
}
}

As you can see, the REST endpoint uses the new @Transactional annotation from Java EE 7 so it can handle theEntityManager in a transactional manner. So if you are like my colleague and don’t like this kind of architectural style, here is what I think of the pros/cons :

Advantages

  • This is a relatively flat architecture. You don’t have any extra layers, interfaces, orUselessAbstractSomethingFactory pattern.
  • Very quick to develop, you develop following your needs
  • Perfect for easy applications (no complex business logic)

Disadvantages

  • No separation of concerns, one class does several things (e.g. the BookBean manages JSF navigation as well as handles entities)
  • Code duplication. The findById method is implemented the same way on both BookBean and BookEndpoint
  • Heavy refactoring. If your application grows in complexity, you might end up refactoring and moving to an EJB Centric architectural style

EJB Centric Style

This is the most common architectural style : it uses separation of concerns. The EJB layer deals with theEntityManager and other complex business logic, while the BookBean and BookEndpoint only deal with respectively JSF and REST concerns. This looks like this :

EJB Centric
The BookEJB is a stateless session bean that does all the database access and orchestrates other external services. The code looks like this :

BookEJB
@Stateless
public class BookEJB {
@PersistenceContext(unitName = "sampleJavaEEEJBCentricPU")
private EntityManager em;
// ...
public Book findById(Long id) {
return em.find(Book.class, id);
}
public void update(Book entity) {
em.merge(entity);
}
public void delete(Book deletableEntity) {
em.remove(em.merge(deletableEntity));
}
}

Both the BookBean and BookEndpoint get a BookEJB injected and delegate all the entity management. The REST endpoint can then look like this :

BookEndpoint
@Path("/books")
public class BookEndpoint {
@Inject
private BookEJB bookService;
// ...
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/xml")
public Response findById(@PathParam("id") Long id) {
Book entity = bookService.findByIdWithRelations(id);
if (entity == null) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok(entity).build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/xml")
public Response update(Book entity) {
bookService.update(entity);
return Response.noContent().build();
}
@DELETE
@Path("/{id:[0-9][0-9]*}")
public Response deleteById(@PathParam("id") Long id) {
Book deletableEntity = bookService.findById(id);
if (deletableEntity == null) {
return Response.status(Status.NOT_FOUND).build();
}
bookService.delete(deletableEntity);
return Response.noContent().build();
}
}

As you can see, the BookEndpoint deals with all the REST interactions (building a Response, error status…) and delegates the other concerns to the EJB. I’m not showing the BookBean code but it would look very similar.

Advantages

  • Seperation of concerns, each class does it’s own job
  • If you add another type of interface (let’s say a SOAP Web Servies), you reuse the EJB layer
  • Perfect for complex applications
  • Scales better than the previous architectural style

Disadvantages

  • Adds an extra layer to the application, but thanks to the no-interface view, in most cases you don’t even need to add an interface (so it’s just one class to add)

Rest Centric Style

Thanks to JAX-RS 2.0, we have now a Client API, meaning that we can finally invoke a REST web service in a standard way. We can then put the REST endpoint in the center of our application and the BookBean will use the JAX-RS Client API to invoke it :

REST centric

In this configuration the REST endpoint becomes the central point of your external invocations, deals with theEntityManager and do all the complex business logic. The BookEndpoint code looks similar to what I’ve showed you so far. The interesting part is in the BookBean that uses the Client API extensively:

BookBean
@Named
@ConversationScoped
public class BookBean implements Serializable {
// ...
private Client client = ClientBuilder.newClient();
private WebTarget target;
@PostConstruct
private void setWebTarget() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String restEndointURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/rest/books/";
target = client.target(restEndointURL);
}
// ...
public Book findById(Long id) {
return target.path("{id}").resolveTemplate("id", id).request(MediaType.APPLICATION_XML).get(Book.class);
}
public String update() {
conversation.end();
try {
if (id == null) {
target.request().post(Entity.entity(book, MediaType.APPLICATION_XML));
return "search?faces-redirect=true";
} else {
target.request().put(Entity.entity(book, MediaType.APPLICATION_XML));
return "view?faces-redirect=true&id=" + book.getId();
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
return null;
}
}
public String delete() {
conversation.end();
try {
target.path("{id}").resolveTemplate("id", getId()).request(MediaType.APPLICATION_XML).delete();
return "search?faces-redirect=true";
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
return null;
}
}
}

As you can see, the Client and WebTarget are used to do GET, POST, PUT and DELETE operations on the REST endpoint.

Advantages

  • Enforces a RESTful style
  • Perfect if you have several external REST clients
  • Eat your own dog food (your JSF backing beans are the first consumers of your REST endpoints)

Disadvantages

  • Your JSF backing beans spend most of their time marshalling/unmarshalling the entities into/from XML (or JSon)

Conclusion

There is no good or bad architecture, there are several use cases and you can create the appropriate style for your needs. Here I just explain 3 different ways of writing the same thing with Java EE 7 but there are many more (another one would be to have several concerns into a single class, such as the Monster Component, another one is to create an extra (useless?) DAOlayer…) :

  • Horizontal Services : each service (JSF, REST, SOAP…) deals with the EntityManager, accesses the database and does the business logic
  • EJB Centric : each interface (JSF, REST, SOAP…) accesses an EJB layer that does most of the processing
  • REST Centric : the front views (JSF, Javascript…) access a REST layer that does all the processing

I hope JBoss Forge 2 will be able to easily generate such diversity, I’ll contribute to make it happen… feel free tojoin the discussion.

Any other style that you use ? What about the ones I’ve presented here, any other ideas ? Download the code and do not hesitate to contribute to it.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Published at DZone with permission of Antonio Goncalves, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}