Declarative Transactions, Session Beans & JDBC
Hi (this is really a newbie question),
If I executed an SQL Update statement in a Stateless Session Bean via JDBC,
is my call to the database enlisted in the container transaction
automatically? (Of course, I am assuming the correct TxRequired settings
are set on the deployment descriptors for the Session Bean.)
Asked in another way, how does JDBC "talk" to the EJB container to let it
know that it is being called within a Transactional Context and that all
activities with the database should then be enlisted in a transaction
automatically? Where does this "smartness" come in? Or does this not happen
at all - do I have to "obtain" the JDBC connection object from the EJB
container instead of writing directly to JDBC?
Thanks in advance,
Abdullah Kauchali
Correct.
I'd also recommend (where possible), doing the DataSource JNDI lookup in
your setSessionContext method and storing it away in a member variable.
There's usually no reason to do it on every method call.
-- Rob
Abdullah Kauchali wrote:
Okay,
After some investigations, this is what I've learned:
1. To get automatic transactional enlistment (in a distributed tx), you
have to make your EJB container aware of the JDBC datasource (viz. you have
to create a Transactional DataSource). This is done by creating necessary
entries in a configuration XML file so that the container can connect to the
JDBC datasource when fired-up;
2. You then only create your Connection object via a reference (JNDI to be
exact) to the connection object and NOT directly with JDBC (this was my
confusion in fact). Something like this:
//obtain the conduit to the JNDI resource manager factory
javax.sql.DataSource objDS = (javax.sql.DataSource)
context.lookup("~some jndi
reference~");
//now get the connection object - notice no "javax" but "java"
java.sql.Connection objCon = objDS.getConnection();
3. By doing 2. above you are actually using a "Resource Manager Connection
Factory" to get your Connection object for subsequent SQL Updates;
4. As long as your JDBC driver supports the javax.sql.DataSource interface
and provided Transactional Context is propagated from any root call to your
worker Session Bean, you get automatic transaction enlistment of the SQL
Updates with your EJB container;
Please correct me if I have concluded wrongly,
Regards
Abdullah
"Abdullah Kauchali" <ak@ak> wrote in message
news:[email protected]...
Hi (this is really a newbie question),
If I executed an SQL Update statement in a Stateless Session Bean viaJDBC,
is my call to the database enlisted in the container transaction
automatically? (Of course, I am assuming the correct TxRequired settings
are set on the deployment descriptors for the Session Bean.)
Asked in another way, how does JDBC "talk" to the EJB container to let it
know that it is being called within a Transactional Context and that all
activities with the database should then be enlisted in a transaction
automatically? Where does this "smartness" come in? Or does this nothappen
at all - do I have to "obtain" the JDBC connection object from the EJB
container instead of writing directly to JDBC?
Thanks in advance,
Abdullah Kauchali
Similar Messages
-
NON-transactional session bean access entity bean
We are currently profiling our product using Borland OptmizeIt tool, and we
found some interesting issues. Due to our design, we have many session beans which
are non transactional, and these session beans will access entity beans to do
the reading operations, such as getWeight, getRate, since it's read only, there
is no need to do transaction commit stuff which really takes time, this could
be seen through the profile. I know weblogic support readonly entity bean, but
it seems that it only has benefit on ejbLoad call, my test program shows that
weblogic still creates local transaction even I specified it as transaction not
supported, and Transaction.commit() will always be called in postInvoke(), from
the profile, we got that for a single method call, such as getRate(), 80% time
spent on postInvoke(), any suggestion on this? BTW, most of our entity beans are
using Exclusive lock, that's the reason that we use non-transactional session
bean to avoid dead lock problem.
ThanksSlava,
Thanks for the link, actually I read it before, and following is what I extracted
it from the doc:
<weblogic-doc>
Do not set db-is-shared to "false" if you set the entity bean's concurrency
strategy to the "Database" option. If you do, WebLogic Server will ignore the
db-is-shared setting.
</weblogic-doc>
Thanks
"Slava Imeshev" <[email protected]> wrote:
Hi Jinsong,
You may want to read this to get more detailed explanation
on db-is-shared (cache-between-transactions for 7.0):
http://e-docs.bea.com/wls/docs61/ejb/EJB_environment.html#1127563
Let me know if you have any questions.
Regards,
Slava Imeshev
"Jinsong HU" <[email protected]> wrote in message
news:[email protected]...
Thanks.
But it's still not clear to me in db-is-shared setting, if I specifiedentity
lock as database lock, I assumed db-is-shared is useless, because foreach
new
transaction, entity bean will reload data anyway. Correct me if I amwrong.
Jinsong
"Slava Imeshev" <[email protected]> wrote:
Jinsong,
See my answers inline.
"Jinsong Hu" <[email protected]> wrote in message
news:[email protected]...
Hi Slava,
Thanks for your reply, actually, I agree with you, we need to
review
our db
schema and seperate business logic to avoid db lock. I can not say,guys,
we need
to change this and that, since it's a big application and developedsince
EJB1.0
spec, I think they are afraid to do such a big change.Total rewrite is the worst thing that can happen to an app. The
better aproach would be identifying the most critical piece and
make a surgery on it.
Following are questions in my mind:
(1) I think there should be many companies using weblogic serverto
develop
large enterprise applications, I am just wondering what's the maintransaction/lock
mechanism that is used? Transional session / database lock,
db-is-shared
entity
I can't say for the whole community, as for my experience the standard
usage patthern is session fasades calling Entity EJBs while having
Required TX attribute plus plain transacted JDBC calls for bulk
reads or inserts.
is the dominant one? It seems that if you speficy database lock,
the
db-is-shared
should be true, right?Basically it's not true. One will need db-is-shared only if thereare
changes
to the database done from outside of the app server.
(2) For RO bean, if I specify read-idle-timeout to 0, it shouldonly
load
once at the first use time, right?I assume read-timeout-seconds was meant. That's right, but if
an application constantly reads new RO data, RO beans will be
constantly dropped from cache and new ones will be loaded.
You may want to looks at server console to see if there's a lot
of passivation for RO beans.
(3) For clustering part, have anyone use it in real enterpriseapplication?
My concern, since database lock is the only way to choose, how aboutthe
affect
of ejbLoad to performance, since most transactions are short live,if high
volume
transactions are in processing, I am just scared to death about
the
ejbLoad overhead.
ejbLoad is a part of bean's lifecycle, how would you be scared ofit?
If ejbLoads take too much time, it could be a good idea to profile
used SQLs. Right index optimization can make huge difference.
Also you may want cosider using CMP beans to let weblogic
take care about load optimization.
(4) If using Optimization lock, all the ejbStore need to do
version
check
or timestamp check, right? How about this overhead?As for optimistic concurrency, it performs quite well as you can
use lighter isolation levels.
HTH,
Slava Imeshev
"Jinsong Hu" <[email protected]> wrote in message
news:[email protected]...
We are using Exclusive Lock for entity bean, because of we do
not
want
to
load
data in each new transaction. If we use Database lock, that means
we
dedicate
data access calls to database, if database deadlock happens,
it's
hard
to
detect,
while using Exclusive lock, we could detect this dead lock in
container
level.
The problem is, using Exclusive concurrency mode you serialize
access to data represented by the bean. This aproach has negative
effect on ablity of application to process concurrent requests.As
a
result the app may have performance problems under load.
Actually, at the beginnning, we did use database lock and usingtransactional
The fact that you had database deadlocking issues tells that
application logic / database schema may need some review.
Normally to avoid deadlocking it's good to group database
operations mixing in updattes and inserts into one place so
that db locking sequence is not spreaded in time. Moving to
forced serialized data access just hides design/implementation
problems.
session bean, but the database dead lock and frequent ejbLoad
really
kill
us,
so we decided to move to use Exclusive lock and to avoid dead
lock,
we
change
some session bean to non-transactional.Making session beans non-transactions makes container
creating short-living transactions for each call to entity bean
methods. It's a costly process and it puts additional load to
both container and database.
We could use ReadOnly lock for some entity beans, but since weblogicserver will
always create local transaction for entity bean, and we found
transaction
commit
is expensive, I am arguing why do we need create container leveltransaction for
read only bean.First, read-only beans still need to load data. Also, you may seeRO
beans
contanly loading data if db-is-shared set to true. Other reason
can
be
that
RO semantics is not applicable the data presented by RO bean (forinstance,
you have a reporting engine that constantly produces "RO" data,
while
application-consumer of that data retrieves only new data and neverasks
for "old" data). RO beans are good when there is a relatively stable
data
accessed repeatedly for read only access.
You may want to tell us more about your app, we may be of help.
Regards,
Slava Imeshev
I will post the performance data, let's see how costful
transaction.commit
is.
"Cameron Purdy" <[email protected]> wrote:
We are currently profiling our product using Borland
OptmizeIt
tool,
and we
found some interesting issues. Due to our design, we have
many
session
beans which
are non transactional, and these session beans will access
entity
beans
to
do
the reading operations, such as getWeight, getRate, since
it's
read
only,
there
is no need to do transaction commit stuff which really takes
time,
this
could
be seen through the profile. I know weblogic support readonly
entity
bean,
but
it seems that it only has benefit on ejbLoad call, my test
program
shows
that
weblogic still creates local transaction even I specified
it
as
transaction not
supported, and Transaction.commit() will always be called
in
postInvoke(),
from
the profile, we got that for a single method call, such as
getRate(),
80%
time
spent on postInvoke(), any suggestion on this? BTW, most of
our
entity
beans are
using Exclusive lock, that's the reason that we use
non-transactional
session
bean to avoid dead lock problem.I am worried that you have made some decisions based on an improper
understand of what WebLogic is doing.
First, you say "non transactional", but from your description
you
should
have those marked as tx REQUIRED to avoid multiple transactions
(since
non-transactional just means that the database operation becomesits
own
little transaction).
Second, you say you are using exclusive lock, which you shouldonly
use
if
you are absolutely sure that you need it, (and note that it
does
not
work in
a cluster).
Peace,
Cameron Purdy
Tangosol, Inc.
http://www.tangosol.com/coherence.jsp
Tangosol Coherence: Clustered Replicated Cache for Weblogic
"Jinsong Hu" <[email protected]> wrote in message
news:[email protected]...
> -
Is it usefull syncronized method in session bean?
hi all
I know that each time I call a session bean my appllication server create one instance.
So i wonder if it's a wrong idea declaring each session bean methods syncronized.
RegardsIt's generally not a good practice to call your business classes directly from javascript.
But you can place a mediator (business delegate) java class inbetween and can access the session bean instead.
To access any java class using ajax, you may need a remoting library like DWR or JSON-RPC.
These libraries offer very powerful and easy way to use ajax in your application.
But if you want a more simpler solution, then have a look at libraries like "ajax4jsf" or "ajaxanywhere". -
Flex + Glassfish EJB3 stateless session bean
Hi, I'm new to Flex. We´re in the process of adopting a
front end web technology. In the Server side we have a JavaEE
Application with several EJB3 session beans deployed in Glassfish
V2ur1. I just wonder if someone could lead me to a sample flex
application that access stateless EJB3 session beans that return
Entity Beans. Which is the best approach? Could anybody share some
sample code with me? Thanks a lot.
My mail is [email protected]Hi,
1) First of all you'll need to download and deploy LiveCycle
Data Services or BlazeDS on your application server.
2) Then download the Flex EJB factory from Adobe Exchange (
http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&extid=1089970)
and add it to your Data Services.
3) Declare your session beans as destinations in
remoting-config.xml
I remember having trouble to get it working on Glassfish so
for Flex/EJB3 development I switched to JBoss. Maybe newer versions
of Glassfish and Data Services will work together more easily.
After setting up the server-side part you invoke session
beans just like any other RemoteObjects (see Flex docs).
Good luck :) -
EJB Stateless Session Bean Transactions
I have a stateless session bean.
Its deployment descripter references a JDBC DataSource.
It uses container managed transactions.
If I make JDBC calls, within a business method
of this stateless session bean, with the referred datasource, is it attached
to a container managed transaction?If I make JDBC calls, within a business method
of this stateless session bean, with the referred
datasource, is it attached
to a container managed transaction?IIRC, yes. For CMT, the container will roll back any JDBC actions carried out by a method if it fails. -
Transaction can be applied to stateless session bean
is transaction can be applied to stateless session beanif yes/no why?
Just because a stateless session bean is stateless doesn't mean it doens't hold state. The stateless means it shouldn't hold any client state.
It can hold onto for example the dao objects.
The idea is that you pass all the client state to the sessionbean when calling it.
Eg.
public void doBulkOperation( User user ,string param1, String param2){
operation1( user, param1 );
operation2( user, param2 );
public void operation1( User user ,String param1){
//do some work involving user
public void operation2( User user ,String param2){
//do some work involving user
now suppose that doBulkOperation, operation1, operation2 are declared as transaction required. doBulkOperation starts the transaction if there isn't one running and joins the transaction. Then operation1 and operation2 join in the transaction.
Perfectly safe!
What you're not allowed to do is the following:
privata User user
public void doBulkOperation( User user ,string param1, String param2){
this.user = user;
operation1( param1 );
operation2( param2 );
public void operation1( String param1){
//do some work involving user
public void operation2( String param2){
//do some work involving user
This would be unsafe because concurrent calls will change the user and produce unpredictable results and possibly corrupting data.
It will work perfectly thougn if there is only one user or you're using a statefull session bean providing you don't share that bean with several clients. -
Session Bean Transaction Rollback not working for RuntimeException
Hi,
I am calling a number of JDBC create/update statements within a method in a container managed transaction stateless session bean with transaction attribute set to required. I am running the bean within the embedded OC4J supplied with JDeveloper 10g (10.1.2). For each JDBC call, i connect to a datasource via JNDI containg a pool of connections pointing to an Oracle 10g database (standard J2EE)
If i throw a runtime exception within the method the transaction is NOT rolled back as it should be according to the EJB spec. However, if i setRollbackOnly() on the session bean SessionContext the transaction does roll back.
Has anybody experienced this before?
Is this an OC4J bug?
Thanks
DaveGenerally, for urgent issues it's best to open a SR with Oracle Support rather than posting to the forums.
enlist=dynamic didnt exist in 10.2.0.2.20, but does now. I can't recall what specific version it was introduced though.
enlist=false prevents enlistment in MSDTC transactions, so thats why it's not rolling back in that case.
"transaction branch length 90 is illegal" was a known issue on Vista, is that the OS you're using? It takes a two part fix, and It is resolved by
1) getting up to 10204 ODP (apply the 10204 rdbms patch to your client install)
2) applying SP1 for Vista
Hope it helps,
Greg -
Transaction is not Rolling Back in Stateless Session Bean
Hi,
I am using UserTransaction in Stateless Session bean .
Transaction is not rolling back.
The following code is writen in stateless session bean. In UserTransaction i am
calling Two methods of another stateless session bean.
The problem is if doJob2() method fails, doJob1() method is rolling back. These
two methods consist of SQL statement with different Connection Object from TXDataSource.And
session bean(TestSession) is set to CMT, attribute as "Required".
try{
Context ictx=new InitialContext();
TestHome home=(TestHome)ictx.lookup("TestSession");
utx = sessionCtx.getUserTransaction();
utx.begin();
TestRemote remote=home.create();
remote.doJob1();
remote.doJob2();
utx.commit();
}catch(Exception e)
try{
utx.rollback();
}catch(Exception ex)
System.out.println("unable to rollback"+ex);
if any SQL Exception as occured in doJob2(), its calling method utx.rollback()
in catch block. but SQL statements executed thru. doJob1() are not rolling back.
what might be the reason?
thanks
Ranganath
Thanx Priscilla ,
Transaction is working.
ranganath
"Priscilla Fung" <[email protected]> wrote:
>
>In your ejb-jar.xml, you should specify <transaction-type> element to
>be "Container"
>for container-managed transaction. If you specified it to be "Bean" for
>bean-managed
>transaction, EJB ontainer will suspend the caller's transaction before
>starting
>a new transaction for your doJobX() methods. Thus, doJob1()nd doJob2()
>will be
>executing in different transactions, and thus rolling back doJob2()'s
>transaction
>will have no effect on work done and committed in doJob1()'s transaction.
>
>Regards,
>
>Priscilla
>
>
>"Ranganath" <[email protected]> wrote:
>>
>>
>>
>>I am sending config.xml,deployment descriptors, code snippet for TestSession.
>>i
>>am using weblogic6.0sp2.
>>if you need any aditional info. please let me know.
>>
>>thanks
>>ranganath
>>
>>EJB-JAR.xml
>>
>><?xml version="1.0"?>
>>
>><!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise
>JavaBeans
>>1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>
>>
>><ejb-jar>
>> <enterprise-beans>
>> <session>
>> <ejb-name>TestSession</ejb-name>
>> <home>com.apar.sslbridge.test.TestHome</home>
>> <remote>com.apar.sslbridge.test.TestRemote</remote>
>> <ejb-class>com.apar.sslbridge.test.TestBean</ejb-class>
>> <session-type>Stateless</session-type>
>> <transaction-type>Bean</transaction-type>
>> <resource-ref>
>> <res-ref-name>jdbc/oraclePool</res-ref-name>
>> <res-type>javax.sql.DataSource</res-type>
>> <res-auth>Container</res-auth>
>> </resource-ref>
>> </session>
>> </enterprise-beans>
>> <assembly-descriptor>
>> <container-transaction>
>> <method>
>> <ejb-name>TestSession</ejb-name>
>> <method-intf>Remote</method-intf>
>> <method-name>*</method-name>
>> </method>
>> <trans-attribute>Required</trans-attribute>
>> </container-transaction>
>> </assembly-descriptor>
>></ejb-jar>
>>
>>
>>TestSession CODE:
>>
>>
>> public void doJob1() throws RemoteException
>> {
>> Statement st = null;
>> String query=null;
>> try{
>> con=getConnection();
>> st=con.createStatement();
>> query="insert into x values("+x+++")";
>> System.out.println(query);
>> int rec=st.executeUpdate(query);
>> }catch(SQLException sqle)
>> {
>> System.out.println("SQL Exception "+sqle);
>> throw new RemoteException("RemoteException*****SQLError");
>> } catch (Exception e) {
>> System.out.println("Exception "+e);
>> throw new RemoteException("RemoteException*****GenralError");
>> }
>>}
>>
>>
>> public void doJob2()throws RemoteException
>> {
>> Connection con=null;
>> Statement st = null;
>> String query=null;
>> try{
>> con=getConnection();
>> st=con.createStatement();
>> query="insert into y values("+x+++")";
>> System.out.println(query);
>> int rec=st.executeUpdate(query);
>> }catch(SQLException sqle)
>> {
>> System.out.println("SQL Exception "+sqle);
>> throw new RemoteException("RemoteException*****SQLError");
>> } catch (Exception e) {
>> System.out.println("Exception "+e);
>> throw new RemoteException("RemoteException*****GenralError");
>>}
>>}
>>private Connection getConnection(){
>>try {
>>Connection con = StaticParams.POOL_DATASOURCE.getConnection();
>>return con;
>> } catch(Exception e) {
>> System.out.println("TestBean.getConnection() Unable to get get pool
>>connection
>>" + e);
>> }
>>}
>>
>>
>>
>>
>>"Priscilla Fung" <[email protected]> wrote:
>>>
>>>It should work if you are using TxDataSource. Could you post your
>config.xml,
>>>deployment descriptors, code snippet for TestSession?
>>>
>>>Regards,
>>>
>>>Priscilla
>>>
>>>"Ranganath" <[email protected]> wrote:
>>>>
>>>>Hi,
>>>>
>>>> I am using UserTransaction in Stateless Session bean .
>>>> Transaction is not rolling back.
>>>>
>>>>The following code is writen in stateless session bean. In UserTransaction
>>>>i am
>>>>calling Two methods of another stateless session bean.
>>>> The problem is if doJob2() method fails, doJob1() method is rolling
>>>> back. These
>>>>two methods consist of SQL statement with different Connection Object
>>>>from TXDataSource.And
>>>>session bean(TestSession) is set to CMT, attribute as "Required".
>>>>
>>>> try{
>>>> Context ictx=new InitialContext();
>>>> TestHome home=(TestHome)ictx.lookup("TestSession");
>>>> utx = sessionCtx.getUserTransaction();
>>>> utx.begin();
>>>> TestRemote remote=home.create();
>>>> remote.doJob1();
>>>> remote.doJob2();
>>>> utx.commit();
>>>> }catch(Exception e)
>>>> {
>>>> try{
>>>> utx.rollback();
>>>> }catch(Exception ex)
>>>> {
>>>> System.out.println("unable to rollback"+ex);
>>>> }
>>>> }
>>>>if any SQL Exception as occured in doJob2(), its calling method utx.rollback()
>>>>in catch block. but SQL statements executed thru. doJob1() are not
>>rolling
>>>>back.
>>>>what might be the reason?
>>>>
>>>>thanks
>>>>Ranganath
>>>
>>
>
-
Rollback a transaction in a session bean BMP?
The following code would work correctly if executed in a stateless session bean BMP?
InitialContext ic = new InitialContext();
javax.sql.DataSource dataSource = (javax.sql.DataSource) ic.lookup("java:comp/env/jdbc/OracleDS");
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
Statement stmt = conn.createStatement("UPDATE TABLE_A SET NAME = 'Duke' WHERE ID = 7");
stmt.executeUpdate();
if (someCondition) {
conn.commit();
} else {
conn.rollback();
My question:
It�s possible to rollback a transaction using rollback() from Connection class in a stateless
session bean BMP?Dear JDC member:
With EJB, you can gain the benefit of transactions without performing any transaction programming. That is, your enterprise beans never explicitly issue a begin, commit, or abort statement. The container performs it to you. But you have to tell the container how to do it. As you might know, the deploment descriptor is the place for it.
But nothing prevent you to do do programmatic transaction as you want.. For that case you have to know JTA (Java Transaction API) and more.
Suppose the transaction aborts, you have to throw an exception back to the client or try it again. The issue here is with stateless sesssion beans, there is no in-memory conversational state. You might think to implement javax.ejb.SessionSynchronization interface with your business methods....
You see there is a lot to know. You can take care of transactions in the client code, but it is a bad design.
You have to understand today most application servers (Websphere, Weblogic...) are designed to minimize those issues in order to make developers' tasks easier. The container takes care of transactions.
Be careful when you write stateless session beans BMP (BMP are for entiti beans)
Regards,
Armand Komenan -
Cannot remove stateful session bean when transaction timed out
The transaction timeout is set to 5 minutes. After several operations on the transactional
stateful session bean(implements SessionSynchronization), the transaction timed out
after 5 minutes and I got the IllegalStateException when calling another business
method. After the transaction rolled back, weblogic.ejb20.locks.LockTimedOutException
was thrown when attempting to remove the bean. It seems the lock on the bean was
not released even though the transaction had been rolled back. Does anyone know how
to remove the bean in this kind of situation?
Here is the stacktrace:
####<Jun 11, 2002 2:39:35 PM PDT> <Notice> <EJB> <app1x.zaplet.cc> <server25044server>
<ExecuteThread: '11' for queue: 'default'> <> <23168:7b09681c532dc7e3> <010015> <Error
marking transaction for rollback: java.lang.IllegalStateException: Cannot mark the
transaction for rollback. xid=23168:7b09681c532dc7e3, status=Rolled back. [Reason=weblogic.transaction.internal.TimedOutException:
Transaction timed out after 299 seconds
Xid=23168:7b09681c532dc7e3(3203140),Status=Active,numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds
since begin=299,seconds left=60,activeThread=Thread[ExecuteThread: '11' for queue:
'default',5,Thread Group for Queue: 'default'],ServerResourceInfo[weblogic.jdbc.jts.Connection]=(state=ended,assigned=none),SCInfo[server25044+server25044server]=(state=active),properties=({weblogic.jdbc=t3://10.0.100.93:7001}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=server25044server+10.0.100.93:7001+server25044+,
Resources={})],CoordinatorURL=server25044server+10.0.100.93:7001+server25044+)]>
java.lang.IllegalStateException: Cannot mark the transaction for rollback. xid=23168:7b09681c532dc7e3,
status=Rolled back. [Reason=weblogic.transaction.internal.TimedOutException: Transaction
timed out after 299 seconds
Xid=23168:7b09681c532dc7e3(3203140),Status=Active,numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds
since begin=299,seconds left=60,activeThread=Thread[ExecuteThread: '11' for queue:
'default',5,Thread Group for Queue: 'default'],ServerResourceInfo[weblogic.jdbc.jts.Connection]=(state=ended,assigned=none),SCInfo[server25044+server25044server]=(state=active),properties=({weblogic.jdbc=t3://10.0.100.93:7001}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=server25044server+10.0.100.93:7001+server25044+,
Resources={})],CoordinatorURL=server25044server+10.0.100.93:7001+server25044+)]
at weblogic.transaction.internal.TransactionImpl.throwIllegalStateException(TransactionImpl.java:1486)
at weblogic.transaction.internal.TransactionImpl.setRollbackOnly(TransactionImpl.java:466)
at weblogic.ejb20.manager.BaseEJBManager.handleSystemException(BaseEJBManager.java:255)
at weblogic.ejb20.manager.BaseEJBManager.setupTxListener(BaseEJBManager.java:215)
at weblogic.ejb20.manager.StatefulSessionManager.preInvoke(StatefulSessionManager.java:371)
at weblogic.ejb20.internal.BaseEJBObject.preInvoke(BaseEJBObject.java:117)
at weblogic.ejb20.internal.StatefulEJBObject.preInvoke(StatefulEJBObject.java:169)
at mypackage.MyBean_wbr3eg_EOImpl.addRecipients(MyBean_wbr3eg_EOImpl.java:450)
####<Jun 11, 2002 2:39:37 PM PDT> <Info> <EJB> <app1x.zaplet.cc> <server25044server>
<ExecuteThread: '11' for queue: 'default'> <> <> <010049> <EJB Exception in method:
remove: weblogic.ejb20.locks.LockTimedOutException: The lock request from EJB:AppmailBean
with primary key:21,775,960,933,010,237 timed-out after waiting 0 ms. The transaction
or thread requesting the lock was:Thread[ExecuteThread: '11' for queue: 'default',5,Thread
Group for Queue: 'default'].>
weblogic.ejb20.locks.LockTimedOutException: The lock request from EJB:AppmailBean
with primary key:21,775,960,933,010,237 timed-out after waiting 0 ms. The transaction
or thread requesting the lock was:Thread[ExecuteThread: '11' for queue: 'default',5,Thread
Group for Queue: 'default'].
at weblogic.ejb20.locks.ExclusiveLockManager$LockBucket.lock(ExclusiveLockManager.java:448)
at weblogic.ejb20.locks.ExclusiveLockManager.lock(ExclusiveLockManager.java:258)
at weblogic.ejb20.manager.StatefulSessionManager.acquireLock(StatefulSessionManager.java:226)
at weblogic.ejb20.manager.StatefulSessionManager.acquireLock(StatefulSessionManager.java:216)
at weblogic.ejb20.manager.StatefulSessionManager.preInvoke(StatefulSessionManager.java:310)
at weblogic.ejb20.manager.StatefulSessionManager.remove(StatefulSessionManager.java:754)
at weblogic.ejb20.internal.StatefulEJBObject.remove(StatefulEJBObject.java:86)
at mypackage.MyBean_wbr3eg_EOImpl.remove(MyBean_wbr3eg_EOImpl.java:7308)If a stateful session throws a RuntimeException (your rollback) the container destroys the instance of the bean and all
associated state information is lost, as required by the EJB specification.
If you want to maintain client state it is generally best to use HttpSession objects (if you have a web application)
for short-lived, client-specific data and JPA entities or other database backed storage for long-lived data. -
WebLogic 10.3.0, web-service enabled session beans, and CMT transactions
Does WebLogic 10.3 support CMT for JAX-WS Web-Service enabled EJB 3.0 session beans?
When a client invokes the following Web service:
@WebService
@Stateless
@TransactionManagement( TransactionManagementType.CONTAINER )
public class TestService
@WebMethod
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String echo( @WebParam( name = "param" ) final String param)
Context context = new InitialContext();
TransactionSynchronizationRegisttry registry =
(TransactionSynchronizationRegistry)
context.lookup( "java:comp/TransactionSynchronizationRegistry" );
registry.putResource("foo", "bar");
return param;
}WebLogic throws this exception:
SEVERE: Transaction does not exist
java.lang.IllegalStateException: Transaction does not exist
at weblogic.transaction.internal.TransactionManagerImpl.putResource(TransactionManagerImpl.java:2033)
at weblogic.transaction.internal.TransactionManagerImpl.putResource(TransactionManagerImpl.java:2029)Is this a bug in WL 10.3.0?
Thanks in advance.
Edited by: user572625 on Aug 18, 2011 12:29 AMThis is fixed now. Someone had defined a Servlet for the web service in web.xml that was preventing the EJB container to kick in.
Edited by: user572625 on Aug 25, 2011 11:54 PM -
Setting transaction isolation level in a session bean
Hi all!
In a stateless session bean (EJB3) with container managed transactions I need to set the transaction isolation level to SERIALIZABLE.
The idea is to prevent lost update on database when multiple accesses occur concurrently.
Thanks in advance for your patience,
TommasoHi all!
In a stateless session bean (EJB3) with container managed transactions I need to set the transaction isolation level to SERIALIZABLE.
The idea is to prevent lost update on database when multiple accesses occur concurrently.
Thanks in advance for your patience,
Tommaso -
Not be able to obtain a transacted session within stateless session bean
I need some assistance on creating a transacted session. For some reason while within a stateless session bean, I am unable to create a transacted session even though I'm specifying to create the transacted queue session. Can anyone provide any assistance to me on this? It would be much appreciated.
Here is the code snippets involved with the problem:
Code snipet from ejb-jar.xml:
<session>
<display-name>Initial Request</display-name>
<ejb-name>InitialRequestBean</ejb-name>
<ejb-class>com.raytheon.rds.jms.InitialRequestBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
Code from stateless session bean:
static Logger logger;
private QueueConnectionFactory connectionFactory;
private SessionContext sc;
private Queue requestQueue;
public String processRequest(String msgBody)
logger.log(Level.INFO, "In processRequest(String).", msgBody);
QueueConnection con = null;
QueueSession session = null;
QueueSender sender = null;
TextMessage message = null;
String messageID = null;
QueueReceiver receiver = null;
TemporaryQueue replyQueue = null;
boolean transacted = false;
try
//Create the infrastructure (ie. The connection & the session)
logger.log(Level.FINE, "Creating connection");
con = connectionFactory.createQueueConnection();
logger.log(Level.FINE, "Creating session");
session = con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
//Note: This line above was changed in all possible permutation and still didn't work such as using Session.SESSION_TRANSACTED
transacted = session.getTransacted();
logger.log(Level.FINE, "Is session transacted? : " + transacted);
//Note: This line above is constantly saying false
//Now first, setup the temporary reply queue and its listener
replyQueue = session.createTemporaryQueue();
logger.log(Level.FINE, "Creating receiver/consumer");
receiver = session.createReceiver(replyQueue);
con.start();
//Now create the requestor that will make the request message and put it on the request queue
logger.log(Level.FINE, "Creating Requestor/Producer");
sender = session.createSender(requestQueue);
//Now create the message and make sure that you put the "JMSReplyTo" property to the temporary response queue we just created
message = session.createTextMessage();
message.setJMSReplyTo(replyQueue);
logger.log(Level.FINE, "Created message: " + message.getJMSMessageID());
//Now add the actual info you want to send
message.setText(msgBody);
//Now send the message
logger.log(Level.INFO, "Sending message: " + message.getText());
sender.send(message);
//Now wait until we get a response
logger.log(Level.FINE, "Waiting for the response message");
Message responseMsg = receiver.receive(20000); //Toggle the "0" to specify timeout in millisectionds
//Process the message
logger.log(Level.FINE, "Processing the response message");
if(null != responseMsg)
logger.log(Level.FINE, "responseMsg is : " + responseMsg.toString());
messageID = processMessage(responseMsg);
logger.log(Level.FINE, "Response is : " + messageID);
//close the connection
logger.log(Level.FINE, "Stopping the connection");
con.stop();
catch (Throwable t)
// JMSException could be thrown
logger.log(Level.SEVERE, "Exception Thrown in sendRequest: ", t);
sc.setRollbackOnly();
finally
//Close the sender
if (sender != null)
try
logger.log(Level.FINE, "Closing the sender");
sender.close();
catch (JMSException e)
logger.log(Level.WARNING, "JMSException Thrown when trying to close the sender to the request queue: ", e);
else
logger.log(Level.FINE, "Sender is already closed.");
//Close the receiver
if (receiver != null)
try
logger.log(Level.FINE, "Closing the receiver");
receiver.close();
catch (JMSException e)
logger.log(Level.WARNING, "JMSException Thrown when trying to close the receiver to the request queue: ", e);
else
logger.log(Level.FINE, "Receiver is already closed.");
//Close the session
if (session != null)
try
logger.log(Level.FINE, "Closing the session");
session.close();
catch (JMSException e)
logger.log(Level.WARNING, "JMSException Thrown when trying to close the session to the request queue: ", e);
else
logger.log(Level.FINE, "Session is already closed.");
//Close the connection
if (con != null)
try
logger.log(Level.FINE, "Closing the connection");
con.close();
catch (JMSException e)
logger.log(Level.WARNING, "JMSException Thrown when trying to close the connection to the reply queue: ", e);
else
logger.log(Level.FINE, "Connection is already closed.");
return messageID;
}I found the answer through lots of painful searching.
http://blogs.sun.com/fkieviet/entry/request_reply_from_an_ejb
This weblog from Frank Kieviet from a sun blog explains what's happening behind the scenes.
Then I proceeded to create a Bean-Managed Transaction out of my EJB, which is using EJB 3.0. This requires the tag:
@TransactionManagement(value= TransactionManagementType.BEAN)
Note: I got this information from http://download.oracle.com/docs/cd/B31017_01/web.1013/b28221/servtran001.htm#BAJIBAFF
Then I just added the code specified in Frank's blog and everything is working now. The main portion of the code looks like this now:
//begin the user transaction
ctx.getUserTransaction().begin();
//Create the infrastructure (ie. The connection & the session)
logger.log(Level.FINE, "Creating connection");
con = connectionFactory.createQueueConnection();
//Create the session
logger.log(Level.FINE, "Creating session");
session = con.createQueueSession(false, Session.SESSION_TRANSACTED);
transacted = session.getTransacted();
logger.log(Level.FINE, "Is session transacted? : " + transacted);
//Now create the sender that will make the request message and put it on the request queue
logger.log(Level.FINE, "Creating Sender");
sender = session.createSender(requestQueue);
//Now create the message
message = session.createTextMessage();
//Now add the actual info you want to send
message.setText(msgBody);
logger.log(Level.FINE, "Created message: " + message.getJMSMessageID());
//Now first, setup the temporary reply queue and its listener
replyQueue = session.createTemporaryQueue();
if(null != replyQueue)
logger.log(Level.FINE, "Created temporary queue: " + replyQueue.getQueueName());
else
logger.log(Level.FINE, "Temporary Queue could not be created.");
//make sure that you put the "JMSReplyTo" property to the temporary response queue we just created
message.setJMSReplyTo(replyQueue);
//Now send the message
logger.log(Level.INFO, "Sending message: " + message.getText());
sender.send(message);
//Now start the connection
logger.log(Level.FINE, "Starting the connection");
con.start();
//commit the changes
ctx.getUserTransaction().commit();
ctx.getUserTransaction().begin();
//Create the receiver
logger.log(Level.FINE, "Creating Receiver");
receiver = session.createReceiver(replyQueue);
//Now wait until we get a response
logger.log(Level.FINE, "Waiting for the response message");
Message responseMsg = receiver.receive(20000); //Toggle the "0" to specify timeout in millisectionds
//Process the message
logger.log(Level.FINE, "Processing the response message");
if(null != responseMsg)
logger.log(Level.FINE, "responseMsg is : " + responseMsg.toString());
else
logger.log(Level.FINE, "No response came back.");
messageID = processMessage(responseMsg);
logger.log(Level.FINE, "Response is : " + messageID);
logger.log(Level.FINE, "Transaction is complete");
//commit the changes
ctx.getUserTransaction().commit(); -
Transaction management in stateless session beans.
Hi all,
I am using EJB 1.1.
I have a statless session bean that has two methods- A and B.
which does not involve any database interaction
like inserting/updating/deleting the data in the database.
The process flow is such the client always calls A first followed by the call to B.
I have the Transaction attribute set as TX_REQUIRED at the whole bean level.
Now my question is as follows:
Since it is a stateless bean, ejbCreate() is called for every method's invocation.
So does it mean that a new transaction is started for every method invocation?
Also since a transaction ends by commit/rollback.
The transation associated with the method A/B will never get completed as there is no commit/rollback involved in method implementation.
So how is this transaction ended?
Any more details about the transaction management in stateless session beans is highly appreciated.
Any input at the earliest is highly appreciated.
Thanks in advance.Since it is a stateless bean, ejbCreate() is called for every method's invocation.For stateless session bean , Create() is not delegated to the instance.
So does it mean that a new transaction is started for every method invocation?This depends opon the Tx attribute and sequence of calls. Since you have given Tx_required then if you call any method and there is no Tx context associated with client,then a new TX will be started by container othere wise it will execute in the same TX context as the calling client. Note that client can be jsp or other ejb method.
Also since a transaction ends by commit/rollback.
The transation associated with the method A/B will never get completed >as there is no commit/rollback involved in method implementation.
So how is this transaction ended?If you are using COntainer managed TX then Transaction handling like starting , ending etc is handled by the container. You need not worry about that.
Any more details about the transaction management in stateless session >beans is highly appreciated.
Any input at the earliest is highly appreciated.Some time back I had read the article on how the Transaction management done by container on IBM Site. I dont have URL , but you can search the site.
HTH
-Ashwani -
Probleme with transaction in session beans
Hello.
i create an session bean which call enties beans.
When i execute un example first time, its correct.
when i execute for second time, the methode don't stop.
i think it is problem of transaction.
thank youHi,
It is impossible to answer your with the given information. When ever you are asking a question please put the relavent informatin like code and deployment descriptors. So please do post the required information.
Ashok
Maybe you are looking for
-
Won't turn on, flashing light, loud buzzing when I try to charge it?
My ipod died in April and I got a replacement from the apple store as it was still (just!) under warranty. I woke up in the middle of the night last night because my ipod was flashing - not on and off, just a blank flashing light. I tried turning it
-
Problems with Adobe Acrobat - last resort!
I've tried at the Adobe Macintosh forum, but haven't had any advice that's helped, so thought I'd try here!... I have Adobe CS3 Design Standard Suite, Educational version, running on OS X 10.5.5 on my MacBook Pro. 1 - I cannot update Acrobat from 8.0
-
Read contents of file into outputstream
Can anyone suggest that what are the best methods to read contents of a file (better cater to both conditions: big file size and small file size) into outputstream and send through socket... Thanks.
-
Hi, Help me out on the below issue. We have a labour Contractor - Vendor. whom we pay with TDS and deduct the ESIC contribution also. While post payment for this vendor in FB60 with TDS, we Debit the expense Account GL, The calculation happens correc
-
Always jumps back to special characters like ü,ö,ß
hello, so i have been having problems with my macbook pro recently. it has a US keyboard but i write a lot in german so i have to use special characters like ä,ü,ö,ß which normally is not a problem, because i can just stay longer on the a,u,o,s keys