Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use POJO (instead of EJB) in a Java EE application?

I am currently learning JAVA EE. I use an oracle Java EE 7 tutorial for that. According to this tutorial, section 34.1.4, they used some non-EJB helper classes for the tutorial example. http://docs.oracle.com/javaee/7/tutorial/doc/ejb-basicexamples001.htm

I'm wondering in what cases I should make a class EJB, and in what cases I should use a usual helper class. I have read what the benefits of using EJB are. But are there cases when it's better to use POJOs?

like image 546
Zhenya Avatar asked Mar 18 '23 12:03

Zhenya


2 Answers

The short answer is "always unless you need specific EJB facilities".

The longer answer is the following. Years ago when EJB prior 3.0 were used the EJB was something "heavy". You had to implement interface, inherit your bean from base class etc. Shortly EJB could be used in container only. This means that writing unit tests for EJB was very difficult.

So, people used the following strategy. They implemented everything they can in POJOs wrapped when needed by EJBs. The solution was verbose (because some stuff was duplicated) but very modular and better testable.

Since EJB 3.0 were introduced there is (almost) no difference between POJO or EJB. Actually EJB is a POJO with some annotations. This means that you do not have to create POJO and then wrap it with thin EJB layer. You can just implement everything in your class (call it POJO if you want) and then turn it into EJB using annotations. Still as delegation is good, so as more code is EJB-annotations-less as better.

like image 53
AlexR Avatar answered Apr 06 '23 01:04

AlexR


EJBs components are managed (by the container) which implies some extra overhead. There is an antipattern called Sledgehammer for a Fly:

Describes when EJB, a technology that comes with extra overhead, is chosen over a simple POJO where only lightweight processing is the requirement. Generates additional complexity; no apparent benefit

The solution:

If your code does not use the following container services, use a POJO:

  • Concurrency
  • Entity interaction
  • Interceptors
  • Life cycle management
  • Timers
  • Transaction management

I would add that in many cases, EJBs are used like Service Facades / Services. There are real world scenarios when you want to process business logic using a design pattern (CDI objects or POJOS) instead of just put the logic in a procedural way using only EJBs. Rephrasing : An EJB service facade is the single entry point to a design pattern which resolves complex business needs (if you no need a design pattern don't use it, keep it simple!).

Sources: Sledgehammer for a Fly, Service Facade, Service:

OCM Java EE 6 Enterprise Architect

Real World Java EE Patterns--Rethinking Best Practices

like image 35
Sergio Avatar answered Apr 06 '23 02:04

Sergio