29

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?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • 2
    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 Apr 07 '11 at 10:57
  • 5
    Elad: On the decline - where did you get that idea from? – Heiko Rupp Apr 07 '11 at 10:58
  • 8
    @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 Apr 07 '11 at 11:05
  • 1
    @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 Apr 07 '11 at 11:16
  • Related question: http://stackoverflow.com/questions/2333307/should-enterprise-java-entities-be-dumb – Raedwald Apr 08 '11 at 13:15

7 Answers7

22

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.

Community
  • 1
  • 1
Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
  • You mention pooling as allowing the use of lightweight stubs. CDI also uses stubs, but doesn't use pooling. I rather suspect that pooling is a hold-over from EJB1/2, where it may have been a good idea, that is now pretty much pointless, and perhaps even harmful. – Tom Anderson May 20 '12 at 20:35
  • Pooling might still have its uses, but there's definitely something to say for making it opt-in or opt-out for those situations where it would be needless or harmful. Currently with @Stateless you get everything in one annotation. Anyway, even in EJB3 instantiating a dependency (maybe to an external system) could be expensive, and then pooling is definitely useful. – Arjan Tijms May 21 '12 at 18:43
  • Yes, it all comes down to expensive dependencies. However, i think that's what JCA resource adapeters are for - managing expensive resources, particularly external connections. Using a resource adapter lets you pool just the resource, rather than having to pool the objects the resource is injected into. Sadly, it's much easier to write a pooled EJB than it is to write a resource adapter. – Tom Anderson May 22 '12 at 08:07
  • If a component was expensive to instantiate for reasons other than holding an expensive resource, then pooling it would make sense, but i suspect that is not often the case. Particularly with the use of stubs! – Tom Anderson May 22 '12 at 08:08
  • I agree with you. JCA is one of the most powerful APIs in Java EE that could have been so much more, but never was. For simple things, its API "almost" works, but "just doesn't". With respect to stubs, you can have an instantiate-at-first access pattern if the bean is reasonably cheap to instantiate. – Arjan Tijms May 22 '12 at 15:47
  • @ArjanTijms I have a follow-up question on your answer. I do not get what you mean by "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.". Can you explain what you meant? I can understand that pooling allows EJB instances to be re-used and that is a good thing but I do not see how pooling enables light weight stubs.. – Geek Jul 17 '14 at 12:20
  • 1
    @Geek The proxy does not necessarily have to contain any data or much logic. It could be a small wrapper, that for every invoked method method X only says: "get bean "xyz.foo.kaz" from pool A and invoke method X". Effectively you *could* see this as just doing something like an http request to "A://xyz.foo.kaz/X". The proxy could be very lightweight since it doesn't even need to contain a reference to the real bean, just a "command/request" for the pool. – Arjan Tijms Jul 18 '14 at 20:08
  • 1
    @ArjanTijms I see your point now. Thanks for the follow-up and +1. – Geek Jul 19 '14 at 08:49
  • @TomAnderson what do you mean by pooling being `now pretty much pointless, and perhaps even harmful`? I am starting to learn EJB and don't know much about the cons of pooling – Michel Feinstein May 25 '17 at 01:53
  • @mFeinstein: Pooling saves the cost of allocation, but introduces the costs of maintenance and sweeping during GC. Back when Java's allocation was slow, it was a performance win for objects like EJBs. For [over a decade now](https://www.ibm.com/developerworks/java/library/j-jtp09275/index.html), it's been a loss. The exception is if the object is very expensive to create for some reason; the most common such reason is that it uses a native resource like a TCP socket. Here, i argue that EJBs should not have such a reason. – Tom Anderson May 25 '17 at 09:03
  • @TomAnderson what do you call maintenance and sweeping? I believe DB connection pooling is still relevant then for still being expensive to create right? – Michel Feinstein May 25 '17 at 12:35
  • @mFeinstein DB connection pooling is indeed a different thing, as connections represents resources on the DB that are expensive to create every time. Instance pooling for plain objects that hold no specific resources is indeed debatable. If you have (say) 10.000 of those in memory the GC has more work to do by checking all references. This extra GC strain plus the costs of looking up from the pool is likely bigger than allocating the object when you need it, and GC it right after. Both have gotten really fast in Java. – Arjan Tijms May 26 '17 at 10:54
6

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.

Jay Taylor
  • 13,185
  • 11
  • 60
  • 85
vickirk
  • 3,979
  • 2
  • 22
  • 37
  • http://stackoverflow.com/questions/3587289/ejb-stateless-session-beans-and-stateful-session-bean/3587429#3587429 concurs: "ejbs are usually in service layer as service classes" – Raedwald Apr 07 '11 at 14:35
5

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();
    }
}
Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
  • "Session Beans often server as Facade" would you say that was the main use, to act as a Facade for your domain objects? – Raedwald Apr 07 '11 at 11:27
  • Not the main use, but a very popular. Especially wrt domain objects, the SB also contain logic to query for them and to do the handling of the ORM framework. – Heiko Rupp Apr 07 '11 at 11:31
  • 3
    http://stackoverflow.com/questions/4773927/in-what-situations-are-ejbs-used-are-they-required-in-websites-web-application/4775719#4775719 emphasises "the requirement of having to start and commit/rollback transactions yourself disappears" – Raedwald Apr 07 '11 at 14:58
5

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.
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • @Michael Borgwardt: All those services in first point is even provided by spring . – Dead Programmer Apr 07 '11 at 11:05
  • 3
    @Suresh: So what? EJB containers provided them before Spring existed. – Michael Borgwardt Apr 07 '11 at 11:08
  • "While it's true that anemic domain models are an antipattern..." this sounds like you are contradicting yourself. Are you saying I should not be so concerned about having an anemic domain model? – Raedwald Apr 07 '11 at 11:23
  • 2
    @Raedwald: No, I'm saying there's a difference between forcibly keeping *all* logic out of the domain model, and putting more specialized or complex logic into separate classes to implement separation of concerns. – Michael Borgwardt Apr 07 '11 at 11:29
  • 1
    EJB 3 has no EntityEJBs - EntityBeans are EJB 1.x and 2.x – Heiko Rupp Apr 07 '11 at 11:31
  • http://www.infoq.com/articles/ddd-in-practice seems to disagree: "some application designs put the [business] rules in facade classes, which leads to domain classes becoming "anemic" in terms of business rules logic. This may be an acceptable solution in small size applications, but it is not recommended for mid-size to large enterprise applications that contain complex business rules." – Raedwald Apr 07 '11 at 15:41
  • 3
    @Raedwald: from the same article: "If a business rule logic spans two or more Entity objects, then it should become part of a Service class." - a stateless session EJB is exactly that, a service class. Note that the article also considers service classes part of the domain layer. – Michael Borgwardt Apr 07 '11 at 16:56
  • A relevant article that agrees that when (and only when) logic spans entities it should be in a service class: http://unhandled-exceptions.com/blog/index.php/2008/12/26/services-anemic-domain-models-and-where-does-my-business-logic-go/ – Raedwald Apr 08 '11 at 13:30
3

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.

Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56
  • 1
    Where did you get that last idea from? EJBs are perfect for scaling. – Heiko Rupp Apr 07 '11 at 11:39
  • well if that was true we'd see more highly used portal using them (twitter, facebook, google, ...). As I said if your system makes heavy use of transactions and security then MAYBE EJBs are a good fit, otherwise like in most cases they are an overkill. – Manuel Salvadores Apr 07 '11 at 12:39
  • @msalvadores don't know about twitter but facebook and google have their own frameworks highly configured to what they need. Most businesses can not afford to have huge teams dedicated for this. JEE runs a surprising amount of the worlds businesses, and that is for a reason, ease of deployment, low development costs and good scalability are some of those reasons. At the enterprise level there is nothing (IMHO) that comes close. – vickirk Apr 07 '11 at 13:57
  • @vickirk sorry to disagree, but my experience with EJB differs from yours. As I said, for massive use of transactions and security then fine, EJBs might be a good choice. If you don't care much about transactions and security then EJBs are a waste of time and resources. – Manuel Salvadores Apr 07 '11 at 14:04
  • 2
    I'm not getting into a long discussion, (probably last comment), but if you don't require a transaction/security then it doesn't use one, no extra resources used. but sure if all you want to do is host one trivial service it's overly complex. Your point was scalability, EJBs are scalable and it is trivial to do with all the ejb containers I have used. – vickirk Apr 07 '11 at 14:17
  • @vickirk your concept of a 'trivial' application is rather narrow. There millions of really complex services and applications that don't really need EJBs despite whether they need transactions and/or security. – Manuel Salvadores Apr 07 '11 at 14:32
  • 1
    But with EJBs the pain to manage transactions is greatly reduced to the point that it becomes trivial. This greatly increases robustness for simple and complex applications alike. Under the hood transactions are still complex by nature, but EJB makes them easy. Just as the implementation of a FK is probably complex internally, but your DB makes adding one to a column trivial. – Arjan Tijms Apr 12 '11 at 09:17
2

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 :) .

Majed
  • 917
  • 6
  • 18
1

stateless-and-stateful-enterprise-java-beans

ejb-stateless-session-beans-and-stateful-session-bean

Community
  • 1
  • 1
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112