• Post Reply Bookmark Topic Watch Topic
  • New Topic

Head First EJB - EJBContext question

 
Quang Pham
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Head First EJB - EJB Transactions - Page 480
The book showing how to get to the UserTransaction using EJBContext.
But where can I get the EJBContext?
My first guess is: if I can get hold of the SessionContext I'll be able to get to UserTransaction.
I am stuck right here.
Please help.
Thanks
Quang

[ November 15, 2007: Message edited by: Quang Pham ]
[ November 15, 2007: Message edited by: Quang Pham ]
 
Mike Keith
author
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Quang,

If you are using EJB 2.x then you simply define a SessionContext field in your bean and assign the context in your setSessionContext() method. This method will be called automatically by the server when the bean is created, and then in your code you call getUserTransaction() on the context.

If you are using EJB 3, though, all you need to do is

@Resource UserTransaction tx;

and the UserTransaction will be injected for you automatically :-)
 
Quang Pham
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mike
Thanks for helping me. But it's still confusing because we got Struts Framework with EJB 1.1

What code should I put inside my Action class that enable me to get the SessionContext?

protected MY_TO invokeService(MY_TO myTO)
throws EJBException, RemoteException, NamingException, CreateException {
SeparationReasonInquiry_TO sepReasonTO =
(SeparationReasonInquiry_TO) myTO;
InitialContext ctx;
if (home == null) {
ctx = new InitialContext();
Object o = ctx.lookup("java:comp/env/PilotFacade");
home = (PilotFacadeHome) PortableRemoteObject.narrow(o, PilotFacadeHome.class);
}
PilotFacade remote = home.create();
myTO =
(MY_TO) remote.processTransaction(
"SeparationReasonInquiry",
sepReasonTO);
return myTO;
}
[ November 15, 2007: Message edited by: Quang Pham ]
 
Mike Keith
author
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the looks of it you should not be using bean-managed transactions at all. You should just use a container-managed session bean with transaction attribute of "Required". Then you would not need to start or commit the transaction at all. It would all happen automaticall.
Look in your book under the container-managed transaction section. That should explain what you need to know.
 
Quang Pham
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll keep on reading more.
Thank you
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!