I have an EJB that needs to be a singleton and stateful since it's going to be a sort of connection pool. My questions are:
If I define an EJB with #Singleton annotation, will it then be stateful by default or do I have to define it with #Stateful also?
Can it be annotated with #Stateless?
Tried to find some documentation about this but no luck so far. So anyone with knowledge, please share your wisdom and perhaps a link or two.
The EJB tutorials show that an EJB can be either Singleton or Stateful or Stateless. I have never tried to use more than one of these annotations, but I am fairly convinced that the right thing to do is to use only one of them.
From that link:
Singleton session beans maintain their state between client
invocations
So, to your question:
if I define a EJB with #Singleton annotation will it then be stateful by default or do I have to define it with #Stateful also?
If for Stateful you mean the ability to maintain its state, the answer is: yes, a Singleton will be Stateful by default.
Keep in mind that there are some particular situations in which a Singleton doesn't behave like a Singleton, read this article about this. Generally, you don't run this kind of risk if you are outside of a cluster and avoid using the default constructor: you need to always use references of an EJB by injecting it in another EJB or a web client using:
#EJB MyEJB myEJB;
Finally, have a look at this part of the Java EE 6 tutorial, about EJBs lifecycle, explaining that the main difference between Stateful and other EJBs is the ability to being passivated by the container during its life. This difference is the main reason why the statement "a Singleton is Stateful by default" is not correct strictly speaking, but is correct in the context of your question.
Related
Is it possible to create a DAO in Java EE environment, which uses JPA, but does not need to be a Stateless bean? I am asking because I have a huge number of EJBs, just because I need a few #Resources in the DAOs, i.e. EntityManager and so on.
What would you recommend as a way to simplify DAOs in huge project, it seems to me that having a full EJB (instead of a simple object) for a DAO is eccessive.
DAOs are accessed both from other EJBs and from servlets.
It's possible, but not recommended, to inject an EntityManager into other types of beans (like e.g. CDI managed beans) along with a UserTransaction and then manually manage your transactions.
In Java EE 7, JTA 1.2 contributes CDI compatible extensions for declarative transactions just like EJBs have, but at the moment there's no final release of any Java EE 7 AS yet.
it seems to me that having a full EJB (instead of a simple object) for a DAO is excessive.
Why do you think that? A "full" EJB is probably more lightweight than any other alternative, and almost certainly more lightweight than any home cooked thing you can come up with based on an EntityManager.
Don't forget that EJB beans share their resources automatically and that injection points only get proxies. If you mainly use stateless EJB beans, those proxies are akin to URLs, and not the "real" beans. This makes stateless and local EJB beans incredibly lightweight to inject.
Meaning, if you have a given Service where you inject (say) 10 DAOs, that each have an injected EntityManager, and during a given call 3 DAOs are invoked then only 3 beans are actually used and only 1 EntityManager instance. It really is rather efficient.
You can implement DAO as POJO is you want. But the DAO needs an EntitManager which must come from somewhere. Either
you look it up in the POJO with InitialContext#lookup
you pass it in the constructor of the POJO
You must pay attention that InitialContext#lookup will work only if the parent EJB has declared a dependency to the entity manager, even if it doesn't use it.
Whether it's worth the trouble is a judgment call. Local EJB are very cheap, and having many EJB is not a problem for the app server. It's more a problem of understandability by developpers. (See this other answer of me)
Another question to ask is whether you really need the DAOs. With EJB 3, they become very thin layer of logic, and it's worth pondering the pros and cons
I found a very interesting question and also the answer to that
How to expose an EJB 3.1 as a REST Web Service?
which refers to http://www.adam-bien.com/roller/abien/entry/ejb_3_1_and_rest.
It is a very useful feature. My question is whether the session bean needs to be a singleton or not? The query I quoted states that it should be a singleton session bean meanwhile the original, the query refers to, does not contain this statement. If it has to be a singleton, could you tell me why?
Thank you also in advance, Tamas.
Although there are no constraints about the EJB type of the class implementing REST (in fact this class doesn't even need to be an EJB at all), an easy-to-maintain and scalable approach suggests to use a Stateless bean for the purpose.
Have a look at this interesting article: RESTful Web services: The basics, by A. Rodriguez, that has a section on the subject (with title Be stateless). From that section, let me quote something:
Stateless server-side components, on the other hand, are less complicated to design, write, and distribute across load-balanced servers. A stateless service not only performs better, it shifts most of the responsibility of maintaining state to the client application. In a RESTful Web service, the server is responsible for generating responses and for providing an interface that enables the client to maintain application state on its own.
i am developing a SaaS application by using JavaEE technologies (JPA, EJB, ..)
for multitenancy, i chose 'Shared Database, Separate Schemas' approach and designed the DB (PostgreSQL) like that
basically what i need to do is changing the default schema for user sessions in the application so that users can get their own data from the right schema
my business logic is implemented with EJB (Container-managed) and the app server is glassfishv3
so in my EJBs i am just injecting the EntityManager like this
#PersistenceContext(unitName="DBNAME")
private EntityManager em;
and leaving the transaction management to the glassfish
i tried to write #PostConstruct callbacks for Stateless EJBs injecting DataSource
but getClientInfo() returns null somehow so i can not even see the default schema. The reason why i injected DataSource was because i thought i have to do some low-level stuff to specify the schema.
i know if i manage the transactions in the application instead of leaving them to the app server, i can change the EntityManager values through EMF easily but i wanna keep the Container-managed infrastructure and just change some values at runtime
is there any way to do this with SessionContext or anything else ?
what is the best way of overcoming this issue ?
thanks in advance
#PostConstruct is by definition the wrong way, because it is only a hint to the bean that it has been constructed and its dependencies have been injected. The bean is now in the pool of EJBs waiting for the first service call. Then it will be connected to the client info of that call. After that call the client info is disconnected again.
I think any kind of standard injection and standard container managed persistence stuff will not work in your case because injection is done exactly once (at EJB creation time) but your case would require injection for each service call/transaction _AND your injection would depend on input data - the client request containing the tenant id.
Also: I hope, you have only up to 6 (or so) tenants due to the maintenance and performance burden of that approach. I have never seen this approach working in the wild.
I've recently been given a project to work on that involves writing a web application. I've never done Java EE before. A lot of resources on the web are dated and I'm having trouble figuring out what the current differences are between the various standards and Java technologies.
Originally I thought I really needed EJB 3.1 due to dependency injection, JPA, session management, and web services. I started experimenting with Glassfish but was told that we had to write the thing in Tomcat. So I've been trying to figure out what I need as well as what and how to put into Tomcat to get there. I've begun to question whether I even need EJB at all.
I want to use JFS, I think, for the MVC architecture. In learning about that I've run into both ManagedBeans and CDI, which according to some renders the former obsolete and also seems to provide all the dependency injection stuff I want to enable unit testing. I've also come to realize that I can get JPA outside of EJB in the form of Hibernate and maybe a few others. Additionally it seems that web services, which I don't know that I need anyway, come in the form of another standard I can't think of the name right now and this also can be installed independently.
My major issue here is session management and state. It seems to me that all which remains for EJB to do is provide #Stateless/#Stateful and #Local/#Remote. However, as I understand it, some of this is already exists in the form of session management in the servlet container...but I don't know how much or what the major differences are that I need to account for in order to decide if I need these things at all.
So my question is, what are the basic, essential differences that I need to know in order to decide if EJB is worth looking at or if I have enough in the form of other libraries and technologies? I've been all over google and Usenet and have not been able to find this information anywhere.
Just thought of another bit. As I understand it, the #Stateful bean annotation provides me thread-safe state saving. I'm probably not going to directly use threads, but I know Java does so behind the scenes a lot and suspect EE especially so. When I need to keep state I don't want to be dealing with threads if this already provides it.
ManagedBean
Java EE 6 has three different ways of defining beans that are managed in one way or another:
#javax.faces.bean.ManagedBean
JSF 2.0 introduced this annotation declaring managed beans in faces-config.xml. This annotation is used to access a bean from the Expression Language.
#javax.inject.Named
In an EE 6 container CDI this annotation is a built-in qualifier types to provide a name to a bean, making it accessible through EL.
#javax.annotation.ManagedBean
This annotation attempts to generalize JSF managed beans for use elsewhere in Java EE.
If you deploy in an EE 6 container (If you use Tomcat or another servlet container, you can also get CDI by adding the Weld jar to your web app), then there is really no reason to use #javax.faces.bean.ManagedBean. Just use #javax.inject.Namedand start taking advantage of CDI sevices.
CDI
One of the objectives of CDI specification is to bring together the Web tier and the transactional services, making easy for developers to use EJB along with JSF in web applications of the Java EE platform.
With CDI you have the following services among others : well-defined lifecycle contexts(influenced by seam 2 and conversation scope), Dependency injection, loose coupling facilities like interceptors, decorators and events and portable extensions, which allows third-party frameworks to integrate in the Java EE 6 environment like SEAM 3 extensions
Managed beans and EJB Services
First of all CDI applies to any managed bean. Some managed beans are EJBs. When we need to use the EJB services in a managed bean, we just add a #Stateless, #Stateful or #Singleton annotation. IMO they act as complementary technologies allowing you to have a flexible and gradual development just only adding some annotations.
So, when should we use a session bean instead of a plain managed bean?
When you need some EJB features that CDI is missing : declarative transactions, concurrency management, pooling, remote or web service invocation ,timers and asynchronous method invokation.
Of course you could also get all aspects using third party libraries - but this would introduce additional complexity to your project. In terms of functionality IMHO EJB are the place to implement :
Business logic, allowing you to have a cleaning separation of busniness logic and web tier logic (implemented by "JSF backing beans" which are CDI managed beans but no EJB)
Functionality which makes most sense for components which are entrypoints to the application (endpoints for remote invocations delivered via RMI or HTTP)
Finally if you need EJB services then you need an Aplication Server (eg. GlassFish or Jboss AS) if you only need CDI services you need a Servlet Container(e.g Tomcat) plus CDI libraries.
Do you need the features provided by EJBs, i.e. security and transaction management? If the answer is yes, EJBs might be a good option.
If the answer is no, and you only need dependency injection, CDI could then be a good option.
You can also get similar capabilities with other 3rd party products, like Spring (dependency injection, Spring security, etc), but deciding whether you use one (EJB) or the other (e.g. Spring) is in many of the cases a matter of previous skillset.
In my opinion, if there are no previous constraints, going Java spec compliant is a good investment.
I would suggest you to start with the CDI and proceed to the EJB's (which is really adding one annotation on top of your POJO) if the requirements needs them (just as it was told - transactionality, web services, JMX, timers, EJB asynchronous invocations).
It's quite reasonable to develop an application in which your entry point is an EJB which encompasses your call in the transaction and allows you to define multiple entry points. The EJB then invokes the CDI beans with the business logic in them.
It's also worth noticing that the TomEE is a certified Java EE 6 Web Profile developed on top of the Apache Tomcat.
I was looking for some help on CDI APIs. I'm sorry if my question looks naive, I tried looking on net for some high level description on CDI APIs, but couldn't get it right.
The javadoc says:
Contexts and Dependency Injection (CDI) defines a set of complementary services that help improve the structure of application code.
My question is in EJB 3.X we already have Annotations for helping with DI and injecting resources like PersistenceContext and other kind of resources. So where exactly the CDI APIs will be helpful? In plain web-app/standalone Java programs using J2SE?
EJB 3.0 comes with dependency injection on resource- and EJB-level - which is pretty cool already :-)
What CDI does (and which is even cooler) - it lowers the barrier to dependency injection to so-called "managed beans" (JSR 316) - which (among others) defines the minimal set of preconditions a class needs to benefit from dependency injection. Just slightly simplifying, one can say that all classes in a CDI project are managed beans and therefore are eligable for DI.
To summarize what CDI brings over EJB 3.0 in terms of DI:
you don't need EJBs anymore, CDI basically works with POJOs. That's truly lightweight, because it allows you to use EJBs when you need EJB, not when you need DI.
DI turns stateful - different dependencies live in different scopes - something EJB 3.0 completely fails to deliver.
you can benefit from a typesafe and loosely coupled interceptor mechanism
you can benefit from a typesafe and loosely coupled mechanism
Have a look at the first chapter here, and you'll get the idea :-)
DI in Java EE5 allows you inject only resources like JDBC DataSource, JPA EntityManager, UserTransaction, Web Services, EJBs etc. All this resources was managed by container.
With EE6 and with CDI in particular you aren't restricted to inject only resources - you can inject everything (every bean). Look at annotations which come with CDI specification: #Inject, #Named, #Scope, #Singleton etc.
CDI give you features like events, decorators etc.
Look at this tutorial, it should help you to understand CDI: http://java.dzone.com/articles/cdi-di-p2