Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can i have a private variable in a stateless

 
avihai marchiano
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic