0

I want to be able to log the amount of time any query takes on my db. I'm using MyBatis to query the DB.

Currently, I have a stateless bean that has methods on it like select, update, etc. and clients of my bean (through @EJB annotation) call these methods. On top of this I have a class level interceptor on the stateless db interaction bean that does my logging.

With any call to the stateless db interaction bean i open a session, run the user's query, and then close the session, all in a try finally block. This is nice because then the EJB client doesn't have to worry about closing sessions or logging how long the query took.

A problem arises when an EJB client wants to make two queries to the same db. I can't use an XA datasource because the vendor doesn't support it.

I have a workaround for this where I implemented a similar stateless db interaction bean that doesn't open or close sessions in each select, update, etc. method, but rather through the use of an openSession() and closeSession() method.

My concern is that this is still a stateless bean and it could get destroyed in the middle of a client's transaction causing a rollback. Is that the case? Should I make it a stateful bean?

I also wrote an interceptor to actually call openSession() and closeSession() for the user so they can just annotate their class or method.

Does this seem like a good pattern or is there a common pattern to handle this case that I am missing? Thanks.

1 Answers1

0

If you query only one DB you don't need XA transactions. Now, a transaction can span multiple EJB method calls. If the transaction annotation is REQUIRED on a method and there is an active transaction when the method is called, the method will executed in the scope of the existing transaction. Also a transaction has associated a persistence context, so if you let the container inject the EntityManager (using @PersistenceContext annotation) where you need it your problem is solved. In this case you don't need to manually close the EntityManager.

Bogdan
  • 934
  • 7
  • 13
  • I'm not using entitybeans or any entitymanager though, I'm using mybatis and plain old sql sessions to talk to the database. Any advice? – user1608137 Feb 19 '13 at 20:53
  • Check this discussion on how to use iBatis in EJBs with transactions spanning multiple calls: http://www.mail-archive.com/user-java@ibatis.apache.org/msg16139.html – Bogdan Feb 20 '13 at 08:16
  • And also you should specify in your original question that you are using iBatis. – Bogdan Feb 20 '13 at 08:17