28
votes

I'm currently learning Jave-EE, having plenty of C++ experience and having learned Java SE. I don't understand the purpose of Enterprise Java Beans; can someone clarify this for me. I'm not interested in legacy uses: this is in the context of EJB-3.1 and Java-EE 6.

It seems that some people use them to contain the business logic, for implementing the business layer of the conventional 3-layer architecture. That separates the domain logic from the domain objects, leading to an anemic domain model. But that goes against all my OOD instincts; I agree with Martin Fowler that it is an anti-pattern. Should I relax my objections to an anemic domain model? Or do EJBs have other uses?

7
It IS an anti-pattern, which is why Java EE has on the decline for years. It may have looked like a good idea 10 years ago. I wouldn't relax your correct objections, but rather avoid going into it EJB's in the first place.Elad
Elad: On the decline - where did you get that idea from?Heiko Rupp
@Elad: It seems you haven't looked into Java EE in the last 5 years. It has improved a lot and is very deservedly regaining a lot of popularity.Michael Borgwardt
@Elad: Java EE is a lot more than just a container for EJB's. Even if EJB 3.x hadn't been introduced, it would still be very powerful.Lukas Eder

7 Answers

22
votes

As indicated by several other answers, EJBs are perfect for implementing the service layer. They are a very modern, lightweight kind of bean in Java EE. Despite the name you cannot compare them with the draconian heavy weight EJB2 beasts that were in J2EE. Everyone agrees those were a disaster, but it's not 2002 anymore.

Ever since EJB3 (2006), EJB beans have been a perfectly fine technology.

They help a lot here by providing declarative transactions (every entry method automatically starts a transaction if one is not already in progress, although this can be changed if desired), pooling, security, locking, remoting and then some. See the following answers for some additional details:

Transactions have been explained here, but to add to this: it's not something that's only needed for highly complex, highly secure systems. I would go as far to state it's a basic requirement even when only dealing with databases. If I process a simple order, I want that the inventory and the order are both updated or both not at all. This is as basic as having PKs and FKs in your database to ensure integrity.

EJBs make it trivial to manage transactions. Without EJBs there's a lot of boilerplate code for starting, committing or rolling-back the tx.

One should also not underestimate the benefits of pooling and stubs that EJB provides. It means a bean can have a lot of EJBs injected, and you don't have to worry about them being instantiated each and every time such a bean is created. This would otherwise especially be troublesome when not all EJBs would be used every time.

Because of pooling however, only very lightweight stubs are injected, which are more akin to a kind of URLs that point to an actual instance. These cost next to nothing in terms of memory or cpu overhead to inject.

EJBs also feature annotations to declare them being Singletons, arrange their locking behavior (write locks/read locks), declaring one should be initiated at startup, allow them to manage a so-called extended persistence context (a persistence context not scoped to a TX), etc.

These are all concerns you don't want in your slim entities. In many architectures, a User object for instance is a simple data entity that I want to send across layers. I don't want my User instance to have a sendMsg() method and have a JMS resource as a dependency, so that message sending can suddenly be done from some client. I'm not really sure why people think this is somehow 'natural' and 'OOP'.

In the real world I also don't invoke a sendMsg operation on my friend Joe whenever I want to send him a postcard. Instead, I address a card and bring it to the postoffice or put it in a postbox.

I also don't invoke a bake() operation on a cake. Instead, I put the cake in an oven, etc.

6
votes

Use of Java EE does not automatically imply a anemic domain model, just as you can write code in say java what does not make good use of best practices doesn't mean it's not possible in java. I believe Martin Fowler's point was J2EE (note the use of J2EE and not Java EE) pretty much enforced operation of logic and data. Using POJO based entities allows data and behaviour to modelled appropriately. The "business logic" in your EJBs typically orchestrates application of business logic but more often than not does not actually perform it, it is usually a very thin wrapper.

EJBs thus form your Service API, you need this whichever platform/framework you are using, you need to have something you can physically invoke, it is an entry point. Whether you are implementing using spring, web services etc... You need a service layer, there is nothing stopping this been implemented in Java EE. A rather contrived example

@Stateless
public SomeServiceImpl implements SomeService
    someServiceMethod() {
       delegate.doSomething();
    }
}

public SomeServiceDelegate implements SomeService
    someServiceMethod() {
       modelObject.doSomething();
    }
}

I'm not going into the reasons to prefer EJBs over any other technology, just wanting to point out that using them doesn't mean your implementation can't use best practice.

5
votes

You already cite the "implement business logic" use case.

EJBs - in EJB 3.x Session Beans, Message Driven Beans and in 3.1 the new Singleton Beans indeed allow you implement the biz logic. Session Beans often server as Facade where clients connect to. Those clients can be Servlets to serve content via e.g. HTTP or also "fat" clients that talk over other (more binary) protocols to the EJBs.

Message Driven Beans serve as endpoint of asynchronous communications and can themselves call methods on Session Beans as an example.

All the EJBs have one thing in common, which makes them very attractive: they are managed by a container. So the container takes care of instantiation, pooling, Transactions, Security etc.

If you write in an EJB

@Resource DataSource x;

The container makes sure that when your bean is ready to receive method calls, the variable 'x' contains a suitable data source.

The pooling of Beans allows you to have many more clients connecting to a site than you could do without, as either the instances are shared (Stateless SB) or instances can be swapped out by the container to 2ndary storage if memory is tight and to re-activate them later.

In EJB 3, the old EntityBeans from EJB 1.x and 2.x are gone and replaced by JPA, which builds the domain data model of POJOs, which may either be annotated to provide the relational semantics or the semantics may be provided by external XML files.

With JPA (which does not require EJBs at all), the EJBs often serve to implement the handling of those entities:

@Stateless
public class MyBean {
    @PersistenceContext EntityManager em;

    public Foo getFoo(String name) {
        Query q = em.createQuery("SELECT f FROM Foo f WHERE f.name = :name");
        q.setParameter("name",name);
        return q.getSingleValue();
    }
}
5
votes

A couple of points:

  • EJBs don't exist on their own; they live in an EJB container, which offers you some very useful services through them, such as declarative security, declarative transactions and relatively easy clustering.
  • While it's true that anemic domain models are an antipattern: once your business logic becomes more complex, e.g. when multiple applications operate on the same model, separating most of the logic from the model becomes a matter of separation of concerns.
3
votes

Just a remark from personal experience ...

I don't doubt of the benefits of EJBs, but having had worked with them, I see EJBs only fitting in cases where security and transactions are very important (i.e: financial applications). For 90% of cases you would be just fine without EJBs. Another thing ... scalability and EJBs are not good friends.

2
votes

Some guys tells in discussion like this the EJB become useful in EJB3 not before that, and that is not ture. right it became more powerful specially with the JPA, but EJB1.0 and EJB2.1 still did a lot. maybe they didn't use it in large applications so they say that.

for example POJO can't deal with a Transaction, so in EJB you can specify the transaction type for a specific method is it require a new transaction or it not from the transaction .

in my organization we have ERP build from scratch using and we use the EJB in the Business Logic, it was from 2000 and the EJB was Version 1.0 . and it's not only separate the business tier from the other thiers but it's also separate the system from each other, for Example: finance module is separate from HR module. and if they want to add a new module they can add it without restarting the system and it will integrate with the system in perfect way..

and remember this in the EJB: what you see in the code is nothing and what the EJB container is doing for you is every thing :) .