Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes EJB and other Java EE Technologies and the fly likes Can i have a private variable in a stateless Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Can i have a private variable in a stateless" Watch "Can i have a private variable in a stateless" New topic
Author

Can i have a private variable in a stateless

avihai marchiano
Ranch Hand

Joined: Jan 10, 2007
Posts: 342
Hey,

Can i have a private variable in a stateless session bean (Ejb3)?

Lets say that i want to implement a DAO as a stateless , so i have a CRUD functions.

create, find ...

all of them need to use entity manager (i cant use injection because i dont know the persistence unit name at run time)

So i think to have - private EntityManager em;

and a setEntityManager function.

after i obtain the stateless i will set the entity manager and operate the functions that i want to do.

is it ok to have private varibale?

as i know you can store a state on stateless , but this is exactly what the injection does.

Thank you
Alejandro Dominguez
Greenhorn

Joined: Jun 01, 2007
Posts: 28

as i know you can store a state on stateless , but this is exactly what the injection does.


avihai,
no you can't store state on a stateless session bean, since it doesn't keep a conversational state with the client. The injection mechanism works with the container, not the client. Stateless beans reside in a pool: each time you call a method, one instance is created/drawn from the pool and assigned to the client, but just for the duration of the method invocation. What this means is that you have no guarantee that when you call other methods, you'll be referencing the same instance, maybe yes, maybe not. Note: while developing and with only a client, you might have a "stateful-like" behavior, as there's only one instance in the pool beeing called. This will most likely change in production where there are multiple clients.

Stateless session beans should receive all the needed information either by
1) injection, which you said was not an option for you
2) method params: in your create, find, etc, method, just add the entity manager argument that will be used by the bean

Hope it helps!

Alejandro

PS: Stateless beans can use static private variables, as those will be shared by all instances running on the same classloader


Alejandro<br /> <br />SCJP 5 (SAI)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Can i have a private variable in a stateless
 
Similar Threads
EJB3: when should session beans be used?
Injecting PersistenceContext
difference between jsf beans and ejb
Customizing EntityManager injection for multi-tenancy
How to propograte entity manager in JBoss?