Haven't used EJB3, but by reading a tutorial, EJB3 looks like mostly for manipulating data in database through JPA (of course, it contains other business logic). Just curious, if no database is quired, is it still beneficial to use EJB3 or it just adds complexity to an application? Will POJO be a better choice for implementation?
Big part of EJB benefits is coming from transactions and persistence.
But even without them you may benefit from EJBs. It can give you a proven clustering and balancing model. It can give you the declarative security. It can give you MDBs which are a convenient way to listen to JMS queues/topics and timers.
All above can be done using third-party libraries, such as Spring. EJBs though are highly consistent, while to get, for instance, clustering and security you may need to combine two products, and it's not guaranteed they will work together well and won't need much glue.
EJBs are transactional, distributed components deployed on an app server that manages lifecycle, threading, and other services. Persistence is just one type of EJBs. You still might find stateless, stateful, or message EJBs useful, even if you don't want to use entity beans.
With that said, you can create POJO components that are stateful, stateless, persistent or message-driven. You don't need EJBs; something like Spring can be a good alternative.
Related
We are a complete SOA workshop(Java only) and we use SOAP for the data transfer. Currently we are in a process of centralizing the database work for a specific component so the other components can fetch data from one application using SOAP.
My argument is that it is good to centralize but it adds a lot of latency when adding soap between database calls. I want a RMI/EJB type of implementation so we get serialized object and it reduces the marshaling overhead. I like the way the Ejbs are implemented and would like to use it. But the data that we return is not at all from one table, so, I cannot return a database table entity, the data might be from 20 other tables or more.
So, in our current system we have custom entities which are created to map to heavy sql queries. (not related to one table)
Can ejbs be used for this type of environment? If so, are there libraries that are readily available to map the result of a query to entities?
Unfortunately our in-house system is very old, we use java 1.4.
This can be done, but it is going to be painful. There was a reason EJB 3.0 entity beans were created. It's because dealing with these sorts of complex requirements is really quite difficult to map via the old 2.x entity beans xml files.
If you are really building a new SOA layer to represent your database content, why would you do this with a technology that has been obsolete for almost 10 years?
Worse, building this with EJB 2.x and then using RMI/EJB will bind all of your other applications to this same outdated technology. Very few people would choose to start a new EJB 2.1 project.
I honestly believe that you are better off using SOAP for your service instead of EJB, at least it won't couple you to an obsolete platform. Current best practices prefer REST for entity transfer, and save SOAP for things RPC-style interactions, but there are lots of good libraries for doing your database tables to SOAP mappings, many of which are out-of-the-box for RDMS's.
Finally, if you are determined to do this, I'd suggest you first do a test. Build a test framework to actually see if the SOAP deserialization is a significant cost component. Compare it to the cost of the network transport. Unless these entities are in the megabyte range, deserialization will be a tiny fraction of your overall application time.
I'm working on an architecture Hibernate/JPA/Spring/Zk, and I multiply the questions these days because I have to learn a lot of framework.
I have a question that leaves me perplexed for several days.
I hear about the "pattern" OpenSessionInView to keep alive a Hibernate transaction to make lazy loading.
Many also say that pattern is not very clean.
And on the other, it is said that PersistentContext extended is not thread safe, and is therefore not suitable for keeping alive the entityManager.
So, what is the real solution to these problems?
I presume that these issues arise from the introduction of ajax which allows more possibilities especially with the use lazy loading to load some heavy Collections when necessary.
For moment, i tried #PersistenceContext in extended mode. It's working...
I had to set it for my JUnit tests, et it's working too in my web application with lazy loading without more configurations.
Is that the evolution of framework (Spring, JPA 2.0) mean that it is now easier and more "clean" work with PersistentContext?
If this is not the case, should we use the OpenSessionInViewFilter from Spring and replace the PersistentContext in transactional mode?
Thank you.
I hear you. I've implemented both patterns in several applications since 2008. Now, I abandon any statetful patterns altogether. When you introduce state to the client, you pose scalability and state management issues: do you merge in client, do you save in user session, what happens when you walk through a wizard and object must be transient before save? How would you synchronize client and serverside state? What happens when db changes--does the client break?
Look at the trend of existing technologies, including Spring MVC: the pattern is to build two projects: 1) restful webservices 2) user interfaces. State is shared through an immutable domain model. Sure you might end up maintain a set of dtos, but they're predictable, cheap, and scale infinitely.
My recommendation? Avoid sending proxied objects over the wire and deal with dtos on the client or a share a domain model with the client if you want to reuse serverside validations. Lazy collections can be loaded via fine-grained api calls through Ajax. That way, you give complete control to the client.
That's how the social web has scaled in the past five years.
I have understood that if I use EJB in Spring context, I get all the same benefits as if I was using it in "pure" EJB3 environment, is this true? I have googled but can't find a definitive, clear answer.
For example, let's say I have a session bean that updates some tables in the database and it throws a System Exception. In "pure" EJB3 environment the transaction is rolled back. What if I for example #Autowire this bean using Spring, does Spring take care of the transaction handling same way as does the EJB3 container? Or what? Does it maybe require some specific configuration or is it fully "automatic"?
I have understood that if I use EJB in
Spring context, I get all the same
benefits as if I was using it in
"pure" EJB3 environment, is this true?
You usually use either POJO + Spring or EJB3. I'm a bit confused by what you mean by "EJB in Spring"...
POJO + Spring and EJB3 are quite close now, and have the same facilities when it comes to declarative transaction management.
I don't know all the details about security, but I would say that both technologies are also very similar.
Actually both Spring and EJB3 rely on other specifications. The important ones are: JPA (persistence), JTA (distributed transaction), JMS (messaging), JDBC (data sources). Good support for that exist in the two technology stacks.
Both technologies have become very flexible and you can choose what to use or not. So you can have EJB3 in an app. server and be very light. Or you can use Spring with all modules which is almost as heavy as a full-fledged app. server.
I think the EJB3 model is still a bit richer, with things like remoting, stateful session beans (SFSB), container-managed transactions, and extended persistence context. Plus the possible support of clustering depending on the app. server. But these are advanced features which are use seldom (and IMO require expertise).
See EJB3 vs Spring
spring has many features, one of which is transaction management, which uses a common abstraction accross all different orm implementations (jpa, raw hibernate, jdbc, jdo etc). The default behavior is that in a transactional method, a runtime exception causes a rollback (which is probably what you want), but you can also fine-tune the rollback rules.
However, none of this requires EJB. If you don't use EJBs (stateless, stateful, mdbs), JPA will be enough for that, and the spring jpa support is excellent. In 90% of the cases spring will provide everything you need without EJBs.
EDIT:
read this about Spring EJB integration
You can have Spring handle transactions and roll back accordingly. You have to configure it to do so, but that's also true of EJBs.
Nothing in life is truly "automatic". You have to tell the code what you want sometime.
The real question is: Why do you think you need both EJBs and Spring? Anything you can do with EJBs can be done using POJOs with Spring. What are EJBs buying you here?
I got very good answers with links to articles, and from those I compiled my understanding that yes, the session beans work the same way regardless of if they are used with Spring or without, as long as the beans are defined in the Spring context with <jee:jndi-lookup>. Also found a good, simple article about this: http://java.dzone.com/articles/ejb-30-and-spring-25
However I can't accept just one answer because to me they are all equally good, but none of them exactly in point :) Could be that my question was not clear enough to start with...
(It was suggested that I post this as an answer to my own question)
As I am learning JSF2, I realized I am not sure what the backing components should be. From design point of view, what is the difference between EJBs and #ManagedBeans?
In the end I am going to use JPA, so EJB is a natural choice for business layer. Is it a good practice to use EJB directly from JSF (as explained here)?
At the moment I'm leaning towards using #ManagedBeans for components which don't need access to business layer (e.g. view helpers) or deal with request/session data. For other purposes, e.g. listing something in a grid, I would directly access EJB.
Is this a good design? Shall I use #ManagedBeans for all backing beans for the sake of clean layer separation, even if in some cases they only delegate to EJB?
Very valid question, but I guess the answer depends on the "strictness" of the approach for your project. There is indeed a bit of redundancy between JSF backing bean and EJB as both implement some business logic.
In a ideal usage of JSF features with converters, rendered, validator, etc. the backing bean could indeed be clean business logic code. But in practice some presentation-related logic frequently leaks in it.
This presentation-related logic should ideally not be in a EJB. This presentation-related logic may depend on the faces package, but not necessary. It's what it does that make it presentation-related or not.
A unified component model has some advantages though. And it's the approach taken by Seam and Spring. In both case, business component with declarative transaction, etc. can be used directly in JSF (Spring does not use EJB but provide a similar model). EJB purist would however say that you should dissociate the two.
So to me it's ultimately a question of taste and size of the project. I can imagine that for a small/medium project using EJB in JSF works fine. For bigger project where this strictness is critical, make sure you don't screw the layers.
In Java EE 6 there is some overlap between the various managed beans: JSF managed beans (#ManagedBean), CDI managed beans (#Named) and EJB beans (#Stateless, #Statefull, #Singleton).
In the view layer I don't see any particular advantage for sticking with #ManagedBean. The CDI variant #Named seems to be able to do the same and more, e.g. provide you with access to the conversion scope.
The current thinking seems to be that eventually the EJB component model will also be retrofitted as a set of CDI annotations. Especially expert group member Reza Rahman frequently hints at this. See e.g. Dependency Injection in Java EE 6 - Part 1
For the time being this has not happened, so EJB beans remain the easiest place to put business logic, especially when JPA is used for persistence.
Nevertheless, whether or not CDI will obtain the capabilities of EJB, IMHO it's still a best practice to use a separate bean for the "backing bean" concept and a separate bean for the "business logic".
The backing bean can be really slim, just containing some references to model objects and services (EJBs). Action Methods of the backing bean can delegate almost directly to the services, but their added value is in providing the user with feedback (adding FacesMessages upon success or failure) and doing small UI modifications (e.g. setting a boolean to false that displayed some dialog).
The Services (business logic) should not know anything about any particular presentation. They should be equally well usable from JSF backing beans, JAX-RS, Servlets, standalone Java SE remote clients or whatever.
Even if all beans would become CDI beans, then this does not change this basic division of responsibility.
Interesting article, didn't knew about that. However, to me this article smells more like a rant towards JSF managed beans. It also tight-couples EJB with JSF. It's maybe interesting in small (personal) applications, but likely not in real world SOA applications where you'd like to have full control over the EJB's been serviced.
As to which one to use for what, I would just stick to #ManagedBean to denote a JSF model --which is tied to one or more specific JSF views. You can perfectly use #EJBs for non-JSF specific business logic and/or datamodels. You can inject #EJBs in a JSF model and delegate it in action methods and maybe also getters/setters, but you should not do the other way round, i.e. do not define the JSF model in an #EJB, this leads to tight coupling and would make #EJBs unuseable outside the JSF context. As far, your design sounds good, as long as you watch to not import anything from javax.faces package in the #EJB class.
By calling EJB from your XHTML, you are introducing tight coupling between the choice of implementation in the view and business tier.
If you use a managed bean to call an EJB, [or even, put in a business delegate], you will be able to change out your business tier completely to Spring without affecting the view layer (XHTML).
Is is technically possible, and very easy for you to (JSR 299) be able to use EJB as your managed bean, and that is probably what these vendors want you to do - get glued to specifics. But whether that is a correct thing to do? - No.
Guys, I HAVE tried reading tons of stuff about EJB. And I don't get it. It seems that most of the authors have a superficial knowledge on it. They basically say it's the business-logic 'stuff'. They don't show it how it interacts with the AppServer and so on, what it does, how, and why?
It is a huge question, but not that huge. It is not like asking what is physics. You basically run your business code inside container which is handling all the connections, lookup, transactions etc. There are alternatives to ejb, e.g. spring.
The question is huge indeed. EJBs in a general sense try to enforce a design pattern that encapsulates all of your reusable code or "business logic" into a specific tier in your architecture. By doing this you can reuse this code for your web/presentation layer and web services for example. EJBs provide a way of persisting your data to a DB.
The trend in java development now a days is POJO driven architectures that leverage dependency injection. Spring is a popular tool to facilitate this design pattern and I would encourage you to explore this instead of EJB.
an enterprise bean is a server-side component that
encapsulates the business logic of an application. The business logic is the code that fulfills the
purpose of the application. In an inventory control application, for example, the enterprise
beans might implement the business logic in methods called checkInventoryLevel and
orderProduct. By invoking these methods, clients can access the inventory services provided
by the application.