Implement Transaction on EJB

Hi! I have a situation - i have more than 2 separate method that will insert and update to different tables in our database. The problem is, all the tables should be successfully commit or rollback. Is it possible to commit all the transaction in different method in 1 method call?How?Attached are sample of the code;
public String CreateInvoice (String today,String mrn,String visitid,String debtor,String invamount,String receiptno,String id, String companycode) //throws SQLException
String InvNo=null;
int IntInvNo;
PreparedStatement pstmtInsert=null;
try
InvNo = assignInvNo();
IntInvNo = Integer.parseInt(InvNo);
conn = establishConnection();
st = conn.createStatement();
conn.setAutoCommit(false);
String sqlInsert="INSERT INTO PA03INVOICE (PA03INVNO,PA03INVDATE,PA03MRN,PA03VISITID,PA03DEBTORCODE,PA03INVAMOUNT,PA03RECEIPTNODEPOSIT,PA03STATUS,PA03ID,PA03STATUSINVOICE,PA03COMPANYCODE,PA03IDPOST,PA03IDCONFIRM,PA03DATEPOST) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pstmtInsert = conn.prepareStatement(sqlInsert);
pstmtInsert.setString(1, InvNo);
pstmtInsert.setString(2, today);
pstmtInsert.setString(3, mrn);
pstmtInsert.setString(4, visitid);
pstmtInsert.setString(5, debtor);
pstmtInsert.setString(6, invamount);
pstmtInsert.setString(7, receiptno);
pstmtInsert.setString(8, "E");
pstmtInsert.setString(9, id);
pstmtInsert.setString(10,"P");
pstmtInsert.setString(11, companycode);
pstmtInsert.setString(12, id);
pstmtInsert.setString(13, id);
pstmtInsert.setString(14, today);
int insertnum =pstmtInsert.executeUpdate();
// pstmtInsert.close();
conn.commit();
catch (SQLException e) {
if (e != null) {
System.out.println(e.getSQLState());
System.out.println(e.getMessage());
System.out.println(e.getErrorCode());
System.out.println("ini error dari--CreateInvoice (String today,String mrn,String visitid,String debtor,String invamount,String receiptno,String id)");
e.printStackTrace();
finally
try{
// rs.close();
st.close();
pstmtInsert.close();
conn.close();
catch(SQLException e2)
System.out.println(e2);
e2.printStackTrace();
return "Insert Done By Ejb - CreateInvoice";
public String updateItemBill (String visitid) //throws SQLException
String InvNo=null;
int IntInvNo;
PreparedStatement pstmtupdate=null;
try
InvNo = assignInvNo();
IntInvNo = Integer.parseInt(InvNo);
conn = establishConnection();
st = conn.createStatement();
conn.setAutoCommit(false);
String sqlUpdate = "UPDATE PA02ITEMBILL SET PA02INVNO=? WHERE PA02VISITID=?";
pstmtupdate = conn.prepareStatement(sqlUpdate);
pstmtupdate.setInt(1, IntInvNo);
int updatenum = pstmtupdate.executeUpdate();
conn.commit();
catch (SQLException e) {
if (e != null) {
System.out.println(e.getSQLState());
System.out.println(e.getMessage());
System.out.println(e.getErrorCode());
System.out.println("error from---updateItemBill (String visitid)");
e.printStackTrace();
finally
try{
pstmtupdate.close();
st.close();
conn.close();
catch(SQLException e2)
System.out.println(e2);
e2.printStackTrace();
return "Insert Done By Ejb";
}

Let me put your question in other words:
"I am facing the problem that a tire of my car sometimes gets flat. In which conditions is it possible? What if I use another road? Does it take longer to reach my destination if I take another road? Is there any chance that my tire gets flat when I turn left when I should turn right?"
Of course I don't tell you which car I drive, which tires I use and which roads I intend to use (I even let the destination unmentioned). Would you be able to answer my questions? Do you have any clue what I am talking about? No? Well, now you know how we feel about your question.
If you explain your problem to us pretend you are explaining it to someone who
- doesn't know your data structure
- doesn't know your source code
- doesn't know how your form is implemented
- doesn't know your forms / database versions
- doesn't know when your problem occurs
- doesn't know anything about your forms application at all
as this would be the case. Please take the time and explain your problem properly to us as by now the only correct answer would be: 42.
cheers

Similar Messages

  • How to start and finish a transaction using EJB 3.0 in JDeveloper

    Hello everybody!
    Does anybody can explain how to start and finish a transaction using EJB 3.0. I need to start a transaction insert some information in some tables and if everything was fine commit the information.
    I put the annotation @TransactionManagement(TransactionManagementType.BEAN) in my session bean and @Resource SessionContext ejbContext; but I don't what anything else I have to do.
    Any help will be appreciate.

    I tryied to use in the client the statement EntityTransaction transaction = myBean.getTransact(); but I receive the EJBException: Cannot use resource level transactions with a container managed EntityManager
    I just need to start a transaction something like this: transaction.begin(); and finish the transaction, something like this: transaction.commit();
    Does anybody can help?

  • How to implement transactions in Tomcat using MySQL

    Hi,
    I am trying to find a way to implement Transactions in Tomcat 4112 using a DBCP connection pool with MySQL (connector/j 3.0.16).
    I am developing a web app using the Struts framework and have tried using JOTM for the transaction implementation. However the JOTM PreparedStatement objects do not support the getGeneratedKeys() method (which i definitely need!!!).
    I have one database with multiple datasources, but the dataase may become much larger and require multiple instances in the future so i want a solution that will scale.
    Can i use the simple JDBC connection.commit() methods? Are these robust? Or is there a simple way to use the base JTA/JTS implementation myself??
    Or is there something like JOTM that implements the full JDBC 3.0 interfaces!!
    lots of questions - sorry...
    thanks
    will crick

    I've got the same problem here.
    I want to implement a HyperlinkListener to a JLabel. (Unlike suggested above, it is only supported by JEditorPane and not JLabel)
    The goal is, that if a user clicks on a Link in a JLabel, the standard browser opens and displays that page.
    Can somebody please help?
    My ultimate goal would be to also be able to add clickable HyperLinks in ToolTip texts, but i guess that'd be even more complicated.

  • Implement Transactions best way, in my application

    Hi all,
    I 'm currently developing an application, 3 - tire one, where its business services are exposed as web services, and those web services directly invokes DAO operations for data base operations.
    I have a question, what is the best way to implement transsactions in my application.
    Do i need to implement transactions in both Service layer as well as DAO layer ? if not is it enough to implemnt in only one layer?
    What are the disadvantages im facing if i implement TX in both layers?
    What are the techniques i have to follow, i mean, are there specific techniques to implement service level transactions compared to DAO transactions?
    can i use spring frameowrk? with AOP support?
    I'm really confused abt the way i should handle transactions, so ur reply will be a huge help for me... thanks in advance
    Thanks a lot
    saj
    PS : if this is not the correct forum to post this questions, could you please let me know the forum i should post this instead
    Edited by: sajhak on Jan 2, 2010 1:39 AM

    First step, what makes you think you need transactions at all. What business rule drives it?

  • Transaction in ejb

    hi,
    I am trying to do transaction using ejb.My bean has two method.The transaction mode of the bean is TX_REQUIRED and is stateful.I am using the jts driver and this is the code i have written.
    public void addemp()throws RemoteException
    try
    usertran.begin();
    Connection con=DriverManager.getConnection("jdbc:oracle:jts8:@DADTest");
    Statement stmt=con.createStatement();
    stmt.executeUpdate("insert into emp1 values(" + "'abdul',23)");
    adddept();
    usertran.commit();
    con.close();
    catch(SQLException e)
    e.printStackTrace();
    public void adddept()throws RemoteException
    try
    Connection con=DriverManager.getConnection("jdbc:oracle:jts8:@DADTest");
    Statement stmt=con.createStatement();
    stmt.executeUpdate("insert into dept2 values(" + "23,'sales','mumbai')");
    con.close();
    catch(SQLException e)
    e.printStackTrace();
    when i run this bean it gives me the following error:
    Creating a new EJB instance
    oracle.oas.container.runtime.CreateException: oracle.oas.container.runtime.CreateException: java.lang.IllegalStateException: Mode TX_BEAN_MANAGED required Mode = TX_SUPPORTS
    javax.ejb.CreateException: oracle.oas.container.runtime.CreateException: oracle.oas.container.runtime.CreateException: java.lang.IllegalStateException: Mode TX_BEAN_MANAGED required Mode = TX_SUPPORTS
    if any one of you can help me on this issue it wil be very grateful.
    thanks in advance.

    It seems like I need to inform my colleages
    that this 200,000-update process is a business logic
    problem.This might help a great bit.
    >
    But what if this is a real life needed process ? We
    already have a good team of architects and
    developers.This statement is questionable. There is a fundamental problem with "one transaction that has more than 200,000 update processes".
    Aside, which also indicates the skill level of this "good team of architects and developers", if it really exists.
    Your group should rethink what is considered a transaction and really analyze the reasons why so many updates need to occur as one batch.
    It would be fantastical if this system could maintain 200,000 live Entity EJB at any one point in time. Either way, you need to rethink, from business terms, what a transaction should be.
    This sounds like a data bulk upload process. There may be no business analysts involved to guide you. You should refer to the "good team" for their advice in addition to this forum. They should be able to provide you with good direction.

  • Default Transaction for EJB

    Hi All,
    Could you please let me know what is the default transactions for EJB 2.0?
    In case of business methods of stateless session beans.
    Thanks

    I believe the default propagation is REQUIRED and the default isolation level for most databases is READ COMMITTED. Or were you looking for something else?
    http://www.ibm.com/developerworks/java/library/j-jtp0514.html
    - Saish

  • Error javax.transaction.TransactionRolledbackException: EJB Exception

    Good afternoon, appeared to me the following error, anyone know what it is?
    oracle.iam.connectors.common.dao.OIMUtil : OIMUtil() : EJB Exception: : javax.transaction.TransactionRolledbackException: EJB Exception

    Hi,
    Thanks for the info..But I can't seem to figure out what wrong in my SP.
    This is my stored proc. and line no.20 pointing to ORA-06152 is the insert statement..
    Can someone help me out please!!
    CREATE OR REPLACE PROCEDURE "DBS1"."INS_EXPENSE"
    ( expense_type in VARCHAR2
    , party_payed_to in VARCHAR2
    , expense_amount in NUMBER
    , bill_date in DATE
    , booked_date in DATE
    , payed_from_acc in VARCHAR2
    , payed_to_acc in VARCHAR2
    , payment_mode in VARCHAR2
    , status in VARCHAR2
    , comment in VARCHAR2
    , entry_userid in VARCHAR2
    , last_chg_userid in VARCHAR2
    , expense_no out NUMBER
    IS
    BEGIN
    select max(EXPENSE_NO) into expense_no from DBS1.EXPENSE;
    expense_no := expense_no + 1;
    insert into DBS1.EXPENSE (EXPENSE_NO,EXPENSE_TYPE,PARTY_PAYED_TO
    ,EXPENSE_AMOUNT,BILL_DATE,BOOKED_DATE,PAYED_FROM_ACC,PAYED_TO_ACC
    ,PAYMENT_MODE,STATUS,COMMENT,ENTRY_TIMESTAMP,ENTRY_USERID
    ,LAST_CHANGE_TIMESTAMP,LAST_CHANGE_USERID) VALUES
    (expense_no,expense_type,party_payed_to,expense_amount,TO_DATE(bill_date,'yyyy-mm-dd')
    ,TO_DATE(booked_date,'yyyy-mm-dd'),payed_from_acc,payed_to_acc,payment_mode,status
    ,comment,SYSDATE,entry_userid,SYSDATE,last_chg_userid);
    END INS_EXPENSE;
    TIA

  • Question about implement the transaction in EJB

    Dear Sir
    I try to do some transaction work in EJB,I builded 6 bean blow
    OrderMgr(session bean) control Order(CMP Entity Bean)
    Istock(session bean) control Item(CMP Entity Bean)
    DeliveryMgr(session bean) control delivery(CMP Entity Bean)
    I try to implement the transaction in session bean OrderMgr Like
    public void submitOrder(int id) {
    Try
    Istock.dosomething
    Delivery.dosomething
    Bookorder.dosomething
    catch (Exception ex) {
    sessionContext.setRollbackOnly();
    But not Rollback not work
    Then I change Session Bean OrderMgr to BMT,write the code blow, but rollback still not work
    sessionContext getUserTransaction().beging();
    Try{
    Istock.dosomething
    Delivery.dosomething
    Bookorder.dosomething
    sessionContext.getUserTransaction().commit();
    catch (Exception ex) {
    sessionContext. rollback();
    Could anyone tellme what's wrong with me code?
      

    If you want to rollback work done by these methods, than you have to make sure that they don't start a new transaction. i.e. they should use tx attribute "required" or "mandatory".
    Istock.dosomething
    Delivery.dosomething
    Bookorder.dosomething

  • Bean-managed transaction with EJB 3.0

    Hi,
    I try to get a bean-managed transaction example running with EJB 3.0 under GlassFish v2ur2.
    In order to demarcate the scenario I have to get me the UserTransaction which I get from the SessionContext. I would like to use it then like: UserTransaction ut = context.getUserTransaction();
    I tried to get the SessionContext with the help of the EJB method setSessionContext which should be called by the container after instance creation.
    However, setting a log output into that method does not show any call of this method.
    So, how can I get this method called or is there another way to get the SessionContext for the UserTransaction to work ?
    Are there any good and fully implemented examples for bean-managed transactions ?
    Thanks for your help.
    Regards

    I found the solution for that my SessionContext was NULL and I could not use the UserTransaction.
    The reason for it is that I injected the EJB with @EJB into my servlet and did a MyBean mybean = new MyBean();
    That leads to a SessionContext which is NULL within my EJB.
    If I use it without instantiating it it works fine.
    Again, thanks for your help. At least it pointed me into the right direction.
    Regards

  • JDBC transactions in EJB 3.0

    We have an EJB 3.0 method that call some jdbc DAO methods. This DAO methods called from controller (servlet) works fine, but when called from EJB method raise the following exception:
    "java.sql.SQLException: Cannot call Connection.commit in distributed transaction. Transaction Manager will commit the resource manager when the distributed transaction is committed."
    I think it is a JTA related error. I don't want to use JTA because I can't modify DAO (its a third party library).
    I've tried annotation @TransactionAttribute(value=SUPPORTS) in the EJB method without success.
    There is anyway to say EJB 3.0 not use JTA?
    Thank's

    Frank, yes, I can modify if it is necessary the datasource but, how can I say in the xxxx-jdbc.xml not to use JTA transactions when this data source is called inside a ejb 3.0 method?
    I'm using Jdev11g and the integrated Web Logic Server.
    Thank's

  • Setting db isolation level on transaction without EJB

              I'm using UserTransaction in the servlet container, to control XA transactions.
              We're not using EJB. How do I set the database isolation level? I'm tempted
              to use java.sql.Connection.setTransactionIsolation(). However, the Sun Javadoc
              for that method says you can't call that after the transaction has started (which
              makes sense). Right now, we're starting the transaction, getting a connection,
              closing the connection, and committing the transaction. I guess that order won't
              work if I want to set the isolation level. Or am I mixing apples and oranges
              here? If I use UserTransaction, is it even appropriate to try to set the isolation
              level on the connection?
              All I really want to do is change the default isolation level. We do not need
              different isolation levels for different use cases. (Not yet, anyway.) We might
              have transactions against two different database instances or other resource managers.
              That's why I want to use UserTransaction and XA transactions.
              Thanks!
              Steve Molitor
              [email protected]
              

    Only committed transactions are replicated to the subscriber.  But it is possible for the report to see dirty data if running in READ UNCOMMITTED or NOLOCK.  You should run your reports in READ COMMITTED or SNAPSHOT isolation , and your replication
    subscriber should be configured with READ COMMITTED SNAPSHOT ISLOATION eg
    alter database MySubscriber set allow_snapshot_isolation on;
    alter database MySubscriber set read_committed_snapshot on;
    as recommended here
    Enhance General Replication Performance.
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Omitting container-transaction in ejb-jar.xml

    Hi,
    This may be an easy answer (although I'm struggling to find onejust now) but if you don't define a <container-transaction> element to the ejb-jar.xml for your EJBs, what transaction attribute is used when using Container Managed Persistence? Are transactions used at all it this scenario or does it default to auto committing after every statement?
    Also, what part does the application server vendor play in this - if any?
    Thanks in advance for any help on this topic.

    I'm still struggling to get a conclusive answer to this issue. Read a few books and the EJB spec itself but nothing seems to give an answer on this issue. This makes me think that it is up to the container if it is not defined.
    Also did some tests on Oracle 9ias and it seems that transactions aren't used when transaction config is not defined for CMT beans as it would only rollback on an error when it was defined. Still need to do some more tests.
    Again, if anyone is able to help shed some light on this then it would be much appreciated.
    Thanks.

  • How to handle Transactions avoiding EJB

    I am using EJB just to use its transaction feature. I know EJB is heavy and there must be other better ways to handle transactions.Could anybody let me know how to JTA (java transaction APIs) in JBDC or if there is any other recommended way to handle Transactions.
    Many Thanks.

    Google for "JTA tutorials".
    It brought back these:
    http://java.sun.com/products/jta/
    http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction4.html#63068

  • Distributed Transaction with EJB 3.0 / JPA

    I did some testing here and it proved to work. I would like someone to tell me if this is really true.
    I have many Stateless Session Bean and Entity Beans, using EJB 3.0 with JPA. The Persistence Unit is configured using JTA transaction type. Some of them are deployed in different app server instances.
    Consider an EJB "A" executing EJBs "B" and "C", both in different containers (remote).
    Both B and C use EntityManager to save data into the database.
    Let�s say "A"�s method doit() first execute "B" succesfully and when executing "C", it fails. Will the whole transaction be rolledback?
    The scenarios I tried it proved to work. But I want a second opinion.
    Thanks
    ps: I was using OracelAS/OC4J

    yes, that is how transactions are supposed to work across app servers. granted, that is assuming that the secondary methods are all using the "REQUIRED" (the default if unspecified) or "SUPPORTS" transaction types. you can change this by using some of the other transaction types, depending on what relationship you want between the various methods.

  • Transaction & non-EJB objects (helper)

    hi i have a question about transactional behavior of non-EJB objects. i'm
              using
              weblogic 6.0 sp1 with ejb 2.0.
              say i have a session bean which starts a container managed transaction. and
              it calls
              out to helper class A(non-EJB), and that helper class A get a connection and
              update
              some tables. after A returns, session bean calls helper class B(non-EJB) in
              the
              same transaction. B is supposed to update some other tables but it throw an
              user
              exception. would the transaction in the session bean be rolled back? would
              it
              also roll back the changes made by helper class A?
              thanks for any help,
              z
              

    Thanks Rob!
              "Rob Woollen" <[email protected]> wrote in message
              news:[email protected]...
              > Ziqiang Xu wrote:
              >
              > > hi i have a question about transactional behavior of non-EJB objects.
              i'm
              > > using
              > > weblogic 6.0 sp1 with ejb 2.0.
              > >
              > > say i have a session bean which starts a container managed transaction.
              and
              > > it calls
              > > out to helper class A(non-EJB), and that helper class A get a connection
              and
              > > update
              > > some tables.
              >
              > You must get the JDBC connection from a TxDataSource.
              >
              > > after A returns, session bean calls helper class B(non-EJB) in
              > > the
              > > same transaction. B is supposed to update some other tables but it
              throw an
              > > user
              > > exception. would the transaction in the session bean be rolled back?
              >
              > Merely throwing an exception from a helper class will not rollback the
              > transaction.
              >
              > Within an EJB, the best way to rollback a tx is to use the
              > EJBContext.setRollbackOnly method.
              >
              > So you could do something like this:
              >
              > session_bean_method() {
              >
              > try {
              > B.foo();
              > } catch (MyException e) {
              > ctx.setRollbackOnly();
              > throw e;
              > }
              >
              > }
              >
              > > would
              > > it
              > > also roll back the changes made by helper class A?
              > >
              >
              > If they are all within a single transaction, then yes. As I mentioned
              before,
              > make sure that you use a TxDataSource for all of your JDBC Connections.
              >
              > -- Rob
              >
              > >
              > > thanks for any help,
              > >
              > > z
              >
              

Maybe you are looking for