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?
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With