Session Beans and EJB3 vs Spring - java

I was curious about the capabilities of Sessions Beans in EJB 3 and whether they can be replaced in a typical mid-scale enterprise application with Spring.
I found this article:
http://drag0sd0g.blogspot.com/2010/01/session-bean-alternative-spring.html
that states the following: "Because of heavy use of annotations,
you can pretty much avoid “XML Hell” using EJB 3; the same cannot be said of Spring.
Moreover, because it is an integral part of the Java EE standard, the EJB container
is natively integrated with components such as JSF, JSP, servlets, the JTA transaction
manager, JMS providers, and JAAS security providers of your application server. With Spring, you have to worry whether your application server fully supports the framework with these native components and other high-performance features like clustering, load balancing, and failover. If you aren’t worried about such things, then Spring is not a bad choice at all"
Do you agree with this statement? The Stateless Sessions Beans used to be considered a very powerful enterprise technology because of the pooling and management capabilities. My question is: when is it really necessary to use EJB 3 instead of or in addition to Spring (assuming a mission critical enterprise application in a large company)?

Looks like yet another Java EE vs. Spring post...
EJB/Java EE and Spring are now two mature, competitive Java-based technology stacks. Often there's no reason to complicate things and mix them up. EJB actually learned and used many ideas from Spring et al.
Neither of them drives you into the XML/configuration hell. Both are fairly easy to get started with, at least with the very basic stuff.
Spring is more than just IoC/SOA/transactions. It's more like a toolbox - it's ready to integrate with, or directly provides, frameworks for ORM and transactions, web/MVC, security, timers/scheduling etc. You can pick exactly the pieces you need. You're not forced to use a container (you can use it in your standalone "desktop" app).
EJB is part of Java EE stack. It is, well, the standard. It's not as broad, flexible as Spring, but it's by definition supported by all Java EE containers.
I prefer Spring for the freedom and being one step ahead.

I don't think there are many cases when the use of EJB 3 instead of Spring is absolutely necessary, but there are cases when using EJB 3 would be considerably easier. As the article states, the main advantages of EJB is the integration with the various other JEE technologies and, as of EJB 3, Enterprise Beans are much simpler to write than in they were in previous versions of the spec.
The classic reason for using EJB over POJOs or other middleware technologies is transactions. If your business logic needs to be transactional then EJB provides simple, declarative transnational demarcation and seamless integration with JTA via the container. While the article suggests that support for clustering, load balancing and performance management is an advantage, this is very much dependant on your choice of JEE application server.
I'd say the key factor in deciding whether to use Spring or EJB 3 is your container. If your target container is a fully JEE 5+ compliant application server and you need support for services such as transactions or messaging then EJB 3 is the obvious choice. If, however, you don't need to integrate with other JEE technologies or are deploying to a light-weight app server then using EJB would simply add unnecessary overhead.

How can anyone think EJB3's defining a data model using a series of java annotations spread out over several classes is superior to Hibernates simple model definition syntax is beyond me.
Its a maintainability nightmare. Why have you got an intersection table? It may be defined almost anywhere in the code base. Some junior programmer plays with the annotations and now your java classes are out of sync with the actual database.
Got a performance issues (and you will). Not only have you got the classic Hibernate "I don't know what SQL it's using" you also have the "I don't know why the table was built like that" problem.

Related

Architecture Choices

I have got an architecture to be chosen based on my requirement assignment.
So, the requirement is to build a web application for the common man , similar to book my show application.
Also, the application should be available via intranet for admin users to manage requests.
Also, it is necessary that i use open source technologies to reduce cost, unless absolutely necessary.
Keeping all these points in mind, i would say i would need the following
a) I would go for a n tier architecture.
b) For presentation tier:- can go with JSP/servlets+JSTL or should i go with JSF
c) For business tier:- Spring MVC or EJB3.0?
d) DAO:- Hibernate/JDBC as DAO layer.
e) Database:- SQL server or Oracle 10g.
Could you please pore in your points so that it can guide me further to go with the right technology and architecture?
Thanks for your expert help in advance.
I am not going to tell you what to choose, but give you some advices how.
First of all, Just want to slightly change your considerations:
b) You should include Spring MVC into this point, because it is abstraction layer on top of servlets and can be easily combined with JSP. BTW Spring guys nowadays prefer Thymeleaf templating engine, so maybe something to consider also. You also definitely want to go for security framework like Spring Security (not sure how it cooperates with a Java EE stack)
c) You probably want to consider Spring IoC (Spring Core) vs EJB3.0. There is also Google Guice framework.
I would suggest you to build your decisions on these factors
What is your and your team expertise with certain technologies
What is your OPs team experience with (Full Java EE app servers or lightweight servlet containers like Tomcat or Jetty)
Is your project going to be bigger monolith (look at advantages of full Java EE app servers) or set of micro-services (look at Spring Boot and it's advantages, also look at Microservices architecture pattern advantages and also PITFALLS -> because it is very popular architectural pattern nowadays, but can lead to various problems like performance problems or production environment complexity)
Are you planning to use Spring related projects (e.g. Spring Data family for connection to different Social networks)
Do you think you'll need to use cashing on app server (consider Hibernate with second level cache)
JDBC vs Hibernate is huge architectural decision, so better read about pros and cons deeply. If you choose JDBC, you probably want to go for Spring JDBC and most importantly some querying framework like JOOQ or QueryDSL.
If you'll go for Hibernate / JOOQ / QueryDsl, you should be safe to choose any SQL DB. Because these frameworks abstracts differences if you avoid using custom features of certain vendor. Said that it is also crucial to take a look at your OPs and admins expertise when choosing DB. If you want to save money on licenses you probably want to take a look at PostgreSQL (enterprise grade open-source DB)
Do you have some enterprise level architects around to consult these decisions with. Clarify early if your app needs to be integrated with some wider enterprise environment. In this case you probably want to take a look at Spring Integration or Apache Camel.
Are you going to have some background regular processing that is not triggered by user requests? Take a look at Spring Batch / Java EE 7 Batch spec.
MOST IMPORTANTLY DO SPEAK WITH YOUR TEAM ABOUT THESE DECISIONS TO INVOLVE SENIOR AND PASSIONATE TEAMMATES. You don't want to hear complaints later.
Don't be afraid to make final decisions. Lack of decision is MUCH WORSE than bad decision.
(I am Spring guy, so I apologize if this sound like your direction should be Spring stack. The Java EE stack definitely has alternatives for most Spring modules, so do your own deep research).
My first post here so request your indulgence. Let me try and answer your questions point by point:
n-tiers architecture - definitely - a UI / REST services / Data store
Presentation tier - I would recommend using an open source Javascript library like Prime NG. Gives you the ability to create great UIs coupled with the fact that they can cleanly call the REST services
Business tier - either Spring boot REST services or JEE 7 REST services. I would stay away from EJBs. Using REST will give you the ability to move to micro services tomorrow
DAO - Hands down JDBC or a very thin wrapper over JDBC for me. Hibernate in my opinion will only complicate things and ability to scale. A well designed JDBC implementation will outperform Hibernate plus will also provide you with an ability to separate optimization concerns
Database - if cost is not a concern Oracle 10G. No comparison to Oracle when it comes to RDBMSs. Note that these are not open source. If you want to go open source Postgresql / MySQL could also be considered. Here I would also recommend you to look at noSQL options like MongoDB / Couchbase
The things I would stay away from are too much of annotation based configuration (do what is really required but not just for the heck of it) or a straight jump into micro services carried to the extreme which may lead to a very difficult production environment to run and manage. Do do make sure that your code reads like a story and tells the business logic rather than only looking like a technology specification. All the best.

What cannot be done without EJB

If JPA does not depend on EJB and it has its own spec. Why do I need EJB ?
What I cannot without EJB ?
I have read the following discussions but I really do not point out why it is still required ?
Why should we use EJB?
https://stackoverflow.com/questions/4464338/why-ejb-is-used-in-enterprise-applications
All of the above answers add important information to the question but misses on one critical point. The main selling point of EJB architecture was distributed component (apart from all
other services such as container managed,transactional, secure etc.). The idea was to enable the business logic to run in distributed environment piggybacking on RMI/IIOP. Although over the years this architectural style proved bad. For distributed computing there were more successfull architecture based on webservices. Distributed components though were made look easy by EJB, had their own share of inherent complexities and performance woes and were later avoided whenever possible. An old but very interesting read on this matter by Martin Fowler can be read here where he is scathing in his attack on the lure of distributed architecture typically being promoted by the likes of EJB. Later people seems to have followed this wisdom and avoided the temptation to jump onto the "distributed architecture" bandwagon. In Java landscape, this was marked by the rise of Spring framework and Rod Johnson's famous book "Expert One-on-One J2EE Development without EJB". People and the likes of me have never missed EJB's since then :-)
P.S. To be fair to EJB specs and the guys working hard on it to improve, they certainly have made fair progress in the past decade and they are much modern and developer friendly. However their "distributed" nature has taken a back seat for good
EJB is just a server side component that servers the request of the user. Each enterprise bean runs in a container which do some maintenance (transaction management, security management, bean life cycle etc.,) on behalf of the user/programmer. Thus it makes the developer to focus on the core job instead of reinventing all alone.
So we can conclude that EJB just reduces the amount of coding done by programmer and let the programmer to focus on the core business logic.
We can do the same without EJBs with some good amount of coding.
Thanks,
JK
EJBs, or enterprise java beans are java classes that can be managed by Java EE container that guarantees services like
bean life cycle
thread management
transaction management etc
Yes, JPA is not a part of Java EE spec now. It moved to JSE. However in past when Entity Beans provided the "standard" bridge between java and relational databases world.
What you cannot do without EJB? I'd say nothing. I mean you can do everything without EJB. And the reason is that there are alternative solutions like Spring or Guice.
And as always you can write lower level code without any framework.

In what situations are EJBs used ? Are they required in websites/ web-application development?

Are EJBS used in database backed websites(that are accessible to all)?
Nothing is ever required of course. If you wanted you could build a web-application as a single large C function behind CGI.
That said, EJBs do make web application development a lot easier. It's not for nothing that they are included in the ultra-lightweight Web Profile of Java EE 6.
EJB does not contain any Database APIs of itself, but it integrates extremely well with JPA. You can inject the EntityManager in it, and the requirement of having to start and commit/rollback transactions yourself disappears. This greatly simplifies your code.
Although you could put DB related code (JPA or JDBC) directly into your Servlets or even JSP pages, this is a practice generally frowned upon. Servlets and JSPs are for display and any business or persistence logic just doesn't belong there. A very practical reason for that is that you can't call into the middle of a JSP page to re-use some piece of business logic.
Keeping your business logic separate is thus a prime virtue of good web applications and EJBs are the designated beans for that in Java EE.
For additional information, see these two answers to similar questions:
Database table access via JPA Vs. EJB in a Web-Application
EJB 3 or Hibernate 3
For the role of EJB in the bigger picture of your web application architecture:
Frameworks for Layering reusable Architectures
EJB's are framework constructs (see here for a high level explanation).
You can use them in lots of situations, to separate concerns like business logic from other concerns like data storage. A high-profile competitor to EJB's (for contrast) is the Spring framework.
In answer to your question, no, they are not REQUIRED for websites and web application development, though they are a way to do it. Other methods of web development in Java are Servlets, JSP.
Servlets are by far the simplest to code. Its feature limited, but for simple web-apps it's plenty.

Why and when to use EJB-based web services?

To transfer data from one system to another, through data interface, by web services, we normally get a result set by SQL query, and format them as a web service endpoint, and allow it to be retrieved by another side.
With EJB 3.0, it seems we can replace the result set by stateless session bean. So are there any advantages over the SQL-based web services? And when should we use it?
This is a very broad question on the system architect level. I will try to answer with my best knowledge without starting a flame war (FYI, I have used both ejb and spring).
As you know, building a stable/robust software application requires many building blocks, such as logging, connection pool, etc. Usually, you can find libraries of these building blocks, but not all of them have common api, so they may require integration. In the worst case, you may have to lock into some vendors. The main idea of EJB 3 (or Java EE) is to provide a more complete set of building blocks (via API, annotation or config), so developers can start working on the core business logic right away with an industry standard API/spec/config without training on the proprietary APIs. Additionally, you can change vendor without changing your codes since API/config are really the industry standard (well, your mileage may vary a lot in the real life. hopefully, the new Java EE will fix it).
Your application may already have some of the main elements that EJB 3 already provides. However, EJB 3 promises to provide more such as ORM mapping, RMI, Load balancing, failover, transactions, dynamic redeployment, logging, system management, thread managing, resource pooling (db connection), security, caching.
As you have an working application already, you can really consider if it is worth of your efford to migrate your codes to a standard system to gain more functionality vs integrate new functionality individually. Additionally, EJB 3.0 (or Java EE) is not really the framework that you can pick. You can also look into other framework, such as Spring.
My suggestion is to really figure what your system requirements, and then pick the right technologies instead of picking up the coolest technologies first.
Good luck

Should I use EJB3 or Spring for my business layer?

My team is developing a new service oriented product with a web front-end. In discussions about what technologies we will use we have settled on running a JBoss application server, and Flex frontend (with possible desktop deployment using Adobe AIR), and web services to interface the client and server.
We've reached an impasse when it comes to which server technology to use for our business logic. The big argument is between EJB3 and Spring, with our biggest concerns being scalability and performance, and also maintainability of the code base.
Here are my questions:
What are the arguments for or against EJB3 vs Spring?
What pitfalls can I expect with each?
Where can I find good benchmark information?
There won't be much difference between EJB3 and Spring based on Performance. We chose Spring for the following reasons (not mentioned in the question):
Spring drives the architecture in a direction that more readily supports unit testing. For example, inject a mock DAO object to unit test your business layer, or utilize Spring's MockHttpRequest object to unit test a servlet. We maintain a separate Spring config for unit tests that allows us to isolate tests to the specific layers.
An overriding driver was compatibility. If you need to support more than one App Server (or eventually want the option to move from JBoss to Glassfish, etc.), you will essentially be carrying your container (Spring) with you, rather than relying on compatibility between different implementations of the EJB3 specification.
Spring allows for technology choices for Persistence, object remoting, etc. For example, we are also using a Flex front end, and are using the Hessian protocol for communications between Flex and Spring.
The gap between EJB3 and Spring is much smaller than it was, clearly. That said, one of the downsides to EJB3 now is that you can only inject into a bean, so you can end up turning components into beans that don't need to be.
The argument about unit testing is fairly irrelevant now - EJB3 is clearly designed to be more easily unit testable.
The compatibility argument above is also kind of irrelevant: whether you use EJB3 or Spring, you're still reliant on 3rd party-provided implementations of transaction managers, JMS, etc.
What would swing it for me, however, is support by the community. Working on an EJB3 project last year, there just weren't a lot of people out there using it and talking about their problems. Spring, rightly or wrongly, is extremely pervasive, particularlty in the enterprise, and that makes it easier to find someone who's got the same problem you're trying to solve.
What are the arguments for or against EJB3 vs Spring?
Spring is always innovating and recognizes real-world constraints. Spring offered simplicity and elegance for the Java 1.4 application servers and didn't require a version of the J2EE specification that no one had access to in 2004 - 2006. At this point it is almost a religious debate that you can get sucked into - Spring + abstraction + open-source versus Java Enterprise Edition (Java EE) 5.0 specifications.
I think Spring complements more than competes with the Java EE specifications. As the features that were once unique to Spring continue to get rolled into the specification, many will argue that EJB 3 offers a 'good enough' feature set for most internal business applications.
What pitfalls can I expect with each?
If your treating this as persistence issue (Spring+JPA) versus EJB3 your really not making that big of a choice.
Where can I find good benchmark information?
I haven't followed the specj benchmark results for sometime, but they were popular for a while. It seems that each vendor (IBM, JBOSS, Oracle, and Sun) get less and less interested in having a compliant server. The lists get Shorter and shorter of certified vendors as you go from 1.3, 1.4. 1.5 Java Enterprise Edition. I think the days of a giant server that is fully compliant with all the specifications are over.
I would definitely recommend EJB3 over spring. We find that it's more streamlined, nicer to code in, and better supported. I have in the past used Spring and found it to be very confusing, and not as well documented as EJB3 (or JPA I guess at the end of the day)
As of EJB3 you no longer have to deal with external config files, and there's only one POJO that you annotate per database table. This POJO can be passed to your web tier without any problems. IDEs like Netbeans can even auto-generate these POJOs for you. We've used EJB3 now as the back end for quite a few large scale applications, and haven't noticed any performance problems.
Your Session Beans can be easily exposed as web services which you could expose to your Flex frontend.
Session beans are easy to lock down at either a method or class level to assign roles and things like that if you need to.
I can't speak that much about spring, as I only tried it out for a few weeks. But my overall impression of it was very poor. That doesn't mean it's bad framework, but our team here has found EJB3 to be the best for the persistence/business layer.
I tend to prefer Spring over EJB3 but my recommendation would be whichever approach you take, try to stick to writing POJOs and use the standard annotations where possible, like the JSR annotations such as #PostConstruct, #PreDestroy and #Resource which work with both EJB3 or Spring so you can pick whichever framework you prefer.
e.g. you could decide on some project to use Guice instead for IoC.
If you want to use pre-request injection such as in a web application you might find Guice is quite a bit faster for dependency injection than Spring.
Session beans mostly boil down to dependency injection and transactions; so EJB3 and Spring are kinda similar really for that. Where Spring has the edge is on better dependency injection and nicer abstractions for things like JMS
i have used a very similar architecture in the past. Spring + Java 1.5 + Actionscript 2/3 when combined with Flex Data Services made it all very easy (and fun!) to code.
though, a Flex front end means you need adequately powerful client machines.
Regarding your question:
What are the arguments for or against EJB3 vs Spring?
I suggest reading the response from the experts: A RESPONSE TO: EJB 3 AND SPRING COMPARATIVE ANALYSIS by Mark Fisher. Read the comments to find Reza Rahman's remarks (EJB 3.0).
Another thing in favor of spring is that most of the other tools / frameworks out there have better support for integration with spring, most of them use spring internally as well (e.g. activemq, camel, CXF etc).
It is also more mature and there are a lot more resources (books, articles, best practices etc) & experienced developers available than for EJB3.
I think EJB is a good component technology but not a good framework.Spring is the best framework available as of today.So i should consider Spring as the best implementation of JEE in the sense of a framework and my recommendation is to use spring in every project which gives us the flexibility to integrate with any component technology easily .

Categories