Spring JDBC - multiple getJdbcTemplate().update(...) calls in same DAO func

Hello there.
I am using pure spring jdbc to connect to a single mysql instance. My DAO class extends JdbcDaoSupport and I am inserting parent and child data into their respective tables by making two calls to getJdbcTemplate().update(...). However, an exception is raised upon call of the second (the child) insert, stating the parent table doesn't have a record with the child expects should be there. I run a query against the parent and child tables, and neither record is there..
I should also note that inserts do occur when i set autocommit to true in the datasource configuration. However, when I set autocommit to false, i get an exception, as described above.
Here are my questions:
1. How does getJdbcTemplate() work when managing a connection?
2. Does calling getJdbcTemplate() each of the two times means I'll get 2 separate (or unique) connections?
3. For question #2, I've also tried creating a local JdbcTemplate variable (let's call it myJdbcTemplate) that points to a single getJdbcTemplate() call. However, when calling myJdbcTemplate.update(...) for both the parent and then the child inserts, I get the same problem.
4. How can I resolve this issue? Must I use some sort of spring jdbc database transaction object?
Any responses or sample code would be appreciated.
Here's my current datasource configuration:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="30"/>
<property name="maxWait" value="1000"/>
<property name="defaultAutoCommit" value="false"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="60"/>
<property name="validationQuery" value="Select sysdate() from dual"/>
</bean>
Edited by: MrVince on Oct 4, 2008 12:27 AM

duffymo wrote:
MrVince wrote:
Hello there.
I am using pure spring jdbc to connect to a single mysql instance. My DAO class extends JdbcDaoSupport and I am inserting parent and child data into their respective tables by making two calls to getJdbcTemplate().update(...). However, an exception is raised upon call of the second (the child) insert, stating the parent table doesn't have a record with the child expects should be there. I run a query against the parent and child tables, and neither record is there..\Not enough information to tell. Can you boil this down to a SSCE?I'm not clear on what you're asking for here. I did a quick google search for the term SSCE but am unclear about what you're talking about here. Can you provide a little more context to what you're asking for? If it takes too long or if it's going to bother you in responding, please disregard this part of my post. Are you asking for a DDL for those two specific tables?
>
Are you using a transaction manager? At the time I posted the question, no. See below for some detail.
Do you have a service that owns the transaction?At the time I posted the question, no. See at the bottom of the post for an update.
>
A parent/child relationship implies a foreign key relationship between the parent primary key and a child field. Does the parent primary key exist? Yes.
Is the child field allowed to be null? No.
How do you acquire the parent primary key to insert into the child field?From this variation of JdbcTemplate's update method:
int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) Using logging, I can confirm a key is being returned. I use this key in the insert of the child. The key is of the expected value.
>
I should also note that inserts do occur when i set autocommit to true in the datasource configuration. However, when I set autocommit to false, i get an exception, as described above.Right, because the parent primary key hasn't been committed yet.
Are you using InnoDB tables? They're the only MySQL tables that enforce referential integrity.
Yes.
Here are my questions:
1. How does getJdbcTemplate() work when managing a connection?What does "work" mean?
You can get an idea by looking at Spring's source for the class. Your question isn't clear.I will rephrase. Will a new connection be retrieved (or attempted to be retrieved) each time getJdbcConnection() is called? Your response in the above quote snippet and the one below seem to address this, however.
>
2. Does calling getJdbcTemplate() each of the two times means I'll get 2 separate (or unique) connections?No, you'll get a reference to the connection that the template has. It doesn't acquire a new connection; it simply uses the connection that was injected into it.
As mentioned just above, this helps me understand. Thanks.
3. For question #2, I've also tried creating a local JdbcTemplate variable (let's call it myJdbcTemplate) that points to a single getJdbcTemplate() call. However, when calling myJdbcTemplate.update(...) for both the parent and then the child inserts, I get the same problem.
4. How can I resolve this issue? Must I use some sort of spring jdbc database transaction object? Of course this should be a single unit of work. You wouldn't want the parent insert to succeed and the children to fail. Exactly. I appreciate you words of understanding and your agreement on what should be done.
Update -- I made some changes since my original post.
Upon googling I found this: [http://sujitpal.blogspot.com/2007/03/spring-jdbctemplate-and-transactions.html]. I decided to use what seemed to be the less invasive declarative approach. I made the following changes to my code:
1. Updated my spring-ws-servlet.xml file to include a DataSourceTransactionManager.
<bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource" />
</bean>2. In the same file, I also configure the TransactionProxyFactoryBean.
     <bean id="myDao"
          class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
          <property name="transactionManager" ref="transactionManager" />
          <property name="target" ref="testResultDao" />
          <property name="proxyTargetClass" value="true" />
          <property name="transactionAttributes">
               <props>
                    <prop key="save*">PROPAGATION_REQUIRED</prop>
                    <prop key="*">PROPAGATION_SUPPORTS,readOnly</prop>
               </props>
          </property>
     </bean>3. I then updated my maven pom.xml to include the following dependencies to support the additions I list above steps #1 and #2.
<dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib-nodep</artifactId>
     <version>2.1_3</version>
</dependency>
<dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-aop</artifactId>
       <version>2.0-m4</version>
</dependency>Here are other portions that may provide some relevance.
The DAO implementation code.
public class TestResultDaoImpl extends JdbcDaoSupport implements TestResultDao {
     public Integer saveStartedTestResult(TestResult testResult) {          
          KeyHolder genKeyHolder = new GeneratedKeyHolder();
          Integer testResultId = null;
                // save parent record
          getJdbcTemplate().update(new SaveResultPac(testResult), genKeyHolder);
          testResultId = new Integer(genKeyHolder.getKey().intValue());
                // save child records
          StringBuilder sqlStmt = new StringBuilder("INSERT into Selected_Transaction " );
          sqlStmt.append("(trans_type_id, test_result_id, create_date, last_update_date) ");
          sqlStmt.append("values(?, ?, sysdate(), ?) ");
          getJdbcTemplate().batchUpdate(sqlStmt.toString(), new SaveSelectedTransactionListBpss(testResultId, testResult.getSelectedTransactionList()));
          return testResultId;
      // more code
}The declaration of the DAO bean, but I have a feeling this probably isn't relevant.
     <bean id="testResultDao" class="org.foobar.dao.impl.mysql.TestResultDaoImpl">
          <property name="dataSource" ref="dataSource"/>
    </bean>I inject testResultDao into there caller bean. Configuration is not listed here.
After following the above three steps, I was able to compile and deploy my code to my local test server. When I execute the code, I still get same Foreign Key violation error.
In light of your recommendations I think I'm going in the right direction. So what am I missing?
Edited by: MrVince on Oct 5, 2008 12:39 AM

Similar Messages

  • Multiple concurrent webservice calls to same operation

    I'm having a problem trying to call the same web service
    operation twice with different parameters. The call is being
    executed twice (I'm passing token data to differentiate the calls
    in the event handler), but the second call's parameters are
    overwriting the first ones. Here is the code:
    wsCodeList["GetTupleList"].arguments.TupleName = "BUSTYPE";
    var call:Object = wsCodeList["GetTupleList"].send();
    call.destination = "busType";
    wsCodeList["GetTupleList"].arguments.TupleName = "ENTTYPE";
    call = wsCodeList["GetTupleList"].send();
    call.destination = "entityType";
    mxml:
    <mx:WebService id="wsCodeList"
    wsdl="
    http://simulacrum.hallmarkins.net/ProgramQuoter/codeList.wso?wsdl"
    useProxy="false" result="onCodeListResult(event)">
    <mx:operation name="GetTupleList" resultFormat="e4x"/>
    </mx:WebService>
    handler:
    private function onCodeListResult(oEvent):void
    var call:Object = oEvent.token;
    var xmlResult:XMLList = oEvent.result;
    trace(call.destination);
    if (call.destination == "busType")
    busType.dataProvider = xmlResult..mspace::description;
    if (call.destination == "entityType")
    entityType.dataProvider = xmlResult..mspace::description;
    I'm getting back only the expected result for the call with
    TupleName "ENTTYPE" twice. So it seems that the parameter is
    getting overwritten before the call has gone out. What am I doing
    wrong?
    Thanx,
    OLIVER

    Called sequentially (from my original post):
    wsCodeList["GetTupleList"].arguments.TupleName = "BUSTYPE";
    var call:Object = wsCodeList["GetTupleList"].send();
    call.destination = "busType";
    wsCodeList["GetTupleList"].arguments.TupleName = "ENTTYPE";
    call = wsCodeList["GetTupleList"].send();
    call.destination = "entityType";
    The docs seem to say this is allow and example found online
    do similar, except the arguments are passed as a parameter to send.
    This doesn't work for me though. The web service I'm using will
    only take the arguments using the arguments object.

  • Multiple Rows Update

    Hi,
    I am creating a form which will display the multiple rows from the table. Is there any way to make multiple rows update at the same time.
    If it is report generated by the query, can we do multiple rows update.
    Regards,
    Munish

    Munish,
    Sounds like what you’re looking for is a tabular form. Click on create page, then choose form, then tabular form and follow the steps of the wizard. This will create a tabular form for you that lets you update multiple rows, add new rows and delete multiple rows.
    Regards,
    Marc

  • Three updates from the same Software Update Group showing as unknown, while all the others are showing as expected.

    Hi
    I have an issue from Septembers security updates where three updates from the same software update group are showing as unknown status rather than required / not required / installed etc.
    There are multiple other updates in the same update group and they are all displaying correctly with the figures I would roughly expect.
    I would have expected if something was wrong with the clients not returning software update scans that all the updates in this software update group (all deployed automatically as part of the same ADR) would show the same status of unknown, rather than just
    three of them.
    The updates in question are: KB2894842, KB2972215 & KB2977629 (First two .net 4.0 and last one IE11).
    Now these updates would largely be not required in our organisation as for the most part we use different versions so I would expect them to show as not required.
    Short of kicking off a mass software update scan cycle I don't know a) why this has happened b) if a scan cycle will fix it. Our clients scan every week and its been several weeks since the updates were deployed, that and the other updates have all reported
    back in.
    Anyone have any ideas? Its making the compliance results look quite poor :(
    Thanks
    Jonathan

    Hi,
    Is there any clue in the logs? Please review WUAHandler.log.
    What is the code you get when you run compliance report, like that in the following thread:
    http://social.technet.microsoft.com/Forums/en-US/becda545-4a5e-4ea3-bd83-8c7026767af5/software-update-compliance-report-showing-status-unknown?forum=configmanagerdeployment

  • Can we use both INSERT and UPDATE at the same time in JDBC Receiver

    Hi All,
    I would like to know is it possible to use both INSERT and UPDATE at the same time in one interface because I have a requirement in which I have to perform both the task.
    user send the file which contains both new and old record and I need to save those in MS SQL database.
    If the record exist then use UPDATE otherwise use INSERT.
    I looked on sdn but didn't find any blog which perform both the things at the same time.
    Interface Requirement
    FILE -
    > PI -
    > JDBC(INSERT & UPDATE)
    I am thinking to use JDBC Lookup but not sure if it good to use for bulk record.
    Can somebody please suggest me something or send me the link of any blog or anything to solve this problem.
    Thanks,

    Hi ,
              If I have understood properly the scenario properly,you are not performing insert and update together. As you posted
    "If the record exist then use UPDATE otherwise use INSERT."
    Thus you are performing either an insert or an update which depends on outcome of a search if the records already exist in database or not. Obviously to search the tables you need " select * from ...  where ...." query. If your query returns some results you proceed with update since this means there are some old records already in database. If your query returns no rows  you proceed with "insert into tablename....." since there are no old records present in database.
      Now perhaps the best method to do the searching, taking a decision to insert or update, and finally insert or update operation is to be done by a stored procedure in MS SQL database.  A stored procedure is a subroutine available to applications accessing a relational database system. Here the application is PI server.   If you need further help on how to write and call stored procedure in MS SQL you can look into these links
    http://www.daniweb.com/web-development/databases/ms-sql/threads/146829
    http://www.sqlteam.com/article/stored-procedures-parameters-inserts-and-updates
    [ This part you can ignore, Since its not sure that you will face this situation
        Still you might face some problems while your scenario runs. Lets consider this scenario, after the stored procedure searches the database it found no rows. Thus you proceed with an insert operation. If your database table is being accessed by multiple applications (or users) other than yours then it is very well possible that after the search operation completed with a null result, an insert/update operation has been performed by some other application with the same primary key. Now when you are trying to insert another row with same primary key you get an error message like "duplicate entry not possible for same primary key value". Thus you need to be careful in this respect. MS SQL has a feature called "exclusive locks ". Look into these links for more details on the subject
    http://msdn.microsoft.com/en-us/library/aa213039(v=sql.80).aspx
    http://www.mssqlcity.com/Articles/Adm/SQL70Locks.htm
    http://www.faqs.org/docs/ppbook/r27479.htm
    http://msdn.microsoft.com/en-US/library/ms187373.aspx
    http://msdn.microsoft.com/en-US/library/ms173763.aspx
    http://msdn.microsoft.com/en-us/library/e7z8d5hf(v=vs.80).aspx
    http://mssqlserver.wordpress.com/2006/11/08/locks-in-sql/
    http://www.mollerus.net/tom/blog/2008/03/using_mssqls_nolock_for_faster_queries.html
        There must be other methods to avoid this problem. But the point is you need to be sure that all access to database for insert/update operations are isolated.
    regards
    Anupam

  • IPhone SDK - Multiple buttons calling the same IBAction

    Hi,
    Can I call the same action with multiple buttons? I´ve just connected
    the action to the buttons in interface builder, but in the header file
    I can´t use - (IBAction)setOperator: (id)sender; as the parameter to the function, it always crash due to uncaught exception. If I use - (IBAction)setOperator; it
    works, but i can´t differentiate wich button was pressed.
    I don´t know if i can set the (id)sender parameter in the interface
    builder. Can anyone help me?
    Thanks,
    Pitteri

    .h file:
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    @interface CalculatorView : UIView {
    IBOutlet UITextField *txtResult;
    IBOutlet UIButton *btnMult;
    IBOutlet UIButton *btnDiv;
    @property (nonatomic, retain) UITextField *txtResult;
    @property (nonatomic, retain) UIButton *btnMult;
    @property (nonatomic, retain) UIButton *btnDiv;
    - (IBAction)setOperator:(id)sender;
    @end
    .m file:
    #import "CalculatorView.h"
    @implementation CalculatorView
    @synthesize btnDiv, btnMult, txtResult;
    - (IBAction)setOperator:(id)sender{
    //if btnMult pressed
    //bla bla bla
    //if btnDiv pressed
    //bla bla bla
    that´s my code. Hope u can help.
    thanks
    @end

  • How to load multiple HTML5 canvas on the same page (the proper method)

    Hi,
    I've been struggling to load multiple canvas animations on the same page. At the beggining I thought that exporting the movies with different namespaces and reloading the libraries in a sequential flow might work, but it doesn't. It always loads just the last animation loaded. More info here: Coding challenge: what am I doing wrong?
    Here is a sample of what I'm doing:
    1st: Publish two flash movies with custom namespaces for "lib" set in the "publish settings": "libFirst" and "libSecond".
    2nd: Edit the canvas tags in the HTML page. One called "firstCanvas" and the other one called "secondCanvas"
    3rd: Edit the javascript like this:
            <script>
                // change the default namespace for the CreateJS libraries:
                var createjsFirst = createjsFirst||{};
                var createjs = createjsFirst;
            </script>
            <script src="//code.createjs.com/easeljs-0.7.1.min.js"></script>
            <script src="//code.createjs.com/tweenjs-0.5.1.min.js"></script>
            <script src="//code.createjs.com/movieclip-0.7.1.min.js"></script>
            <script src="{{assets}}/js/first.js"></script>
            <script>
                function initFirstAnimation() {
                    var canvas, stage, exportRoot;
                    canvas = document.getElementById("firstCanvas");
                    exportRoot = new libFirst.first();
                    stage = new createjsFirst.Stage(canvas);
                    stage.addChild(exportRoot);
                    stage.update();
                    createjsFirst.Ticker.setFPS(libFirst.properties.fps);
                    createjsFirst.Ticker.addEventListener("tick", stage);
            </script>
            <script>
                // change the default namespace for the CreateJS libraries:
                var createjsSecond = createjsSecond||{};
                var createjs = createjsSecond;
            </script>
            <script src="//code.createjs.com/easeljs-0.7.1.min.js"></script>
            <script src="//code.createjs.com/tweenjs-0.5.1.min.js"></script>
            <script src="//code.createjs.com/movieclip-0.7.1.min.js"></script>
            <script src="{{assets}}/js/second.js"></script>
            <script>
                function initSecondAnimation() {
                    var canvas, stage, exportRoot;
                    canvas = document.getElementById("secondCanvas");
                    exportRoot = new libSecond.second();
                    stage = new createjsSecond.Stage(canvas);
                    stage.addChild(exportRoot);
                    stage.update();
                    createjsSecond.Ticker.setFPS(libSecond.properties.fps);
                    createjsSecond.Ticker.addEventListener("tick", stage);
            </script>
    <body onload="initFirstAnimation(); initSecondAnimation();">
    Could someone please reply with the best practice on how to do this? If possible, without the need to reload all the libraries...
    If I only need to show one flash movie at a time, would it be more efficient to cut & paste the canvas tag using jQuery in the DOM and reloading a different lib on it?
    Many thanks!
    #flash #reborn

    I was able to fix it. At the end, it was easier than I thought. Just have to publish using a different "lib" namespace for each movie, load all the scripts at the end of the <body> and then add the following to the onload or ready events:
    $(document).ready(function () {
            var canvas, stage, exportRoot;
            // First movie
            canvas = document.getElementById("firstCanvas");
            exportRoot = new libFirst.first();
            stage = new createjs.Stage(canvas);
            stage.addChild(exportRoot);
            stage.update();
            createjs.Ticker.setFPS(libFirst.properties.fps);
            createjs.Ticker.addEventListener("tick", stage);
            // Second movie
            canvas = document.getElementById("secondCanvas");
            exportRoot = new libSecond.second();
            stage = new createjs.Stage(canvas);
            stage.addChild(exportRoot);
            stage.update();
            createjs.Ticker.setFPS(libSecond.properties.fps);
            createjs.Ticker.addEventListener("tick", stage);
            // Third movie
            canvas = dument.getElementById("thirdCanvas");
            exportRoot = new libThird.third();
            stage = new createjs.Stage(canvas);
            stage.addChild(exportRoot);
            stage.update();
            createjs.Ticker.setFPS(libThird.properties.fps);
            createjs.Ticker.addEventListener("tick", stage);

  • Error while doing multiple object updation from EP ! object lock error

    HI all,
    I am doing multiple  object updation using a standard RFC(BAPI_PROJECT_MAINTAIN). The RFC i am calling from Enterprise portal. I am sending data to RFC one by one. But the error i am getting is object is locked by user so data can't be save.
    Though i am using Lock and unlock method before and after calling RFC the project lock error comes up.
    What might be the reason
    regards
    sandeep

    Hi Sandeep,
    Is the RFC you use for locking in the same model as the bapi BAPI_PROJECT_MAINTAIN? If it is not then you are using two connections for communication with the sap R/3 backend.
    You can do 2 things.
    1. You could add the RFCs for locking in the same model as the BAPI_PROJECT_MAINTAIN
    2. Instead of adding the RFCs in one model synchronize the connections the models use as follows:
    IWDDynamicRFCModel model1 = (IWDDynamicRFCModel) WDModelFactory.getModelInstance(Model1.class);
    IWDDynamicRFCModel model2 = (IWDDynamicRFCModel) WDModelFactory.getModelInstance(Model2.class);
    model1.setConnectionProvider(model2);
    You can do this in the wdDoInit. This will make sure both models use the same connection but closing a connection will close both at the same time.
    The same problem applies to commit/rollback functionality.
    Regards,
    Jeschael

  • Multiple Executions Plans for the same SQL statement

    Dear experts,
    awrsqrpt.sql is showing multiple executions plans for a single SQL statement. How is it possible that one SQL statement will have multiple Executions Plans within the same AWR report.
    Below is the awrsqrpt's output for your reference.
    WORKLOAD REPOSITORY SQL Report
    Snapshot Period Summary
    DB Name         DB Id    Instance     Inst Num Release     RAC Host
    TESTDB          2157605839 TESTDB1               1 10.2.0.3.0  YES testhost1
                  Snap Id      Snap Time      Sessions Curs/Sess
    Begin Snap:     32541 11-Oct-08 21:00:13       248     141.1
      End Snap:     32542 11-Oct-08 21:15:06       245     143.4
       Elapsed:               14.88 (mins)
       DB Time:               12.18 (mins)
    SQL Summary                            DB/Inst: TESTDB/TESTDB1  Snaps: 32541-32542
                    Elapsed
       SQL Id      Time (ms)
    51szt7b736bmg     25,131
    Module: SQL*Plus
    UPDATE TEST SET TEST_TRN_DAY_CL = (SELECT (NVL(ACCT_CR_BAL,0) + NVL(ACCT_DR_BAL,
    0)) FROM ACCT WHERE ACCT_TRN_DT = (:B1 ) AND TEST_ACC_NB = ACCT_ACC_NB(+)) WHERE
    TEST_BATCH_DT = (:B1 )
    SQL ID: 51szt7b736bmg                  DB/Inst: TESTDB/TESTDB1  Snaps: 32541-32542
    -> 1st Capture and Last Capture Snap IDs
       refer to Snapshot IDs witin the snapshot range
    -> UPDATE TEST SET TEST_TRN_DAY_CL = (SELECT (NVL(ACCT_CR_BAL,0) + NVL(AC...
        Plan Hash           Total Elapsed                 1st Capture   Last Capture
    #   Value                    Time(ms)    Executions       Snap ID        Snap ID
    1   2960830398                 25,131             1         32542          32542
    2   3834848140                      0             0         32542          32542
    Plan 1(PHV: 2960830398)
    Plan Statistics                        DB/Inst: TESTDB/TESTDB1  Snaps: 32541-32542
    -> % Total DB Time is the Elapsed Time of the SQL statement divided
       into the Total Database Time multiplied by 100
    Stat Name                                Statement   Per Execution % Snap
    Elapsed Time (ms)                            25,131       25,130.7     3.4
    CPU Time (ms)                                23,270       23,270.2     3.9
    Executions                                        1            N/A     N/A
    Buffer Gets                               2,626,166    2,626,166.0    14.6
    Disk Reads                                      305          305.0     0.3
    Parse Calls                                       1            1.0     0.0
    Rows                                        371,735      371,735.0     N/A
    User I/O Wait Time (ms)                         564            N/A     N/A
    Cluster Wait Time (ms)                            0            N/A     N/A
    Application Wait Time (ms)                        0            N/A     N/A
    Concurrency Wait Time (ms)                        0            N/A     N/A
    Invalidations                                     0            N/A     N/A
    Version Count                                     2            N/A     N/A
    Sharable Mem(KB)                                 26            N/A     N/A
    Execution Plan
    | Id  | Operation                    | Name            | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | UPDATE STATEMENT             |                 |       |       |  1110 (100)|          |
    |   1 |  UPDATE                      | TEST            |       |       |            |          |
    |   2 |   TABLE ACCESS FULL          | TEST            |   116K|  2740K|  1110   (2)| 00:00:14 |
    |   3 |   TABLE ACCESS BY INDEX ROWID| ACCT            |     1 |    26 |     5   (0)| 00:00:01 |
    |   4 |    INDEX RANGE SCAN          | ACCT_DT_ACC_IDX |     1 |       |     4   (0)| 00:00:01 |
    Plan 2(PHV: 3834848140)
    Plan Statistics                        DB/Inst: TESTDB/TESTDB1  Snaps: 32541-32542
    -> % Total DB Time is the Elapsed Time of the SQL statement divided
       into the Total Database Time multiplied by 100
    Stat Name                                Statement   Per Execution % Snap
    Elapsed Time (ms)                                 0            N/A     0.0
    CPU Time (ms)                                     0            N/A     0.0
    Executions                                        0            N/A     N/A
    Buffer Gets                                       0            N/A     0.0
    Disk Reads                                        0            N/A     0.0
    Parse Calls                                       0            N/A     0.0
    Rows                                              0            N/A     N/A
    User I/O Wait Time (ms)                           0            N/A     N/A
    Cluster Wait Time (ms)                            0            N/A     N/A
    Application Wait Time (ms)                        0            N/A     N/A
    Concurrency Wait Time (ms)                        0            N/A     N/A
    Invalidations                                     0            N/A     N/A
    Version Count                                     2            N/A     N/A
    Sharable Mem(KB)                                 26            N/A     N/A
    Execution Plan
    | Id  | Operation                    | Name         | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | UPDATE STATEMENT             |              |       |       |     2 (100)|          |
    |   1 |  UPDATE                      | TEST         |       |       |            |          |
    |   2 |   TABLE ACCESS BY INDEX ROWID| TEST         |     1 |    28 |     2   (0)| 00:00:01 |
    |   3 |    INDEX RANGE SCAN          | TEST_DT_IND  |     1 |       |     1   (0)| 00:00:01 |
    |   4 |   TABLE ACCESS BY INDEX ROWID| ACCT         |     1 |    26 |     4   (0)| 00:00:01 |
    |   5 |    INDEX RANGE SCAN          | INDX_ACCT_DT |     1 |       |     3   (0)| 00:00:01 |
    Full SQL Text
    SQL ID       SQL Text
    51szt7b736bm UPDATE TEST SET TEST_TRN_DAY_CL = (SELECT (NVL(ACCT_CR_BAL, 0) +
                  NVL(ACCT_DR_BAL, 0)) FROM ACCT WHERE ACCT_TRN_DT = (:B1 ) AND PB
                 RN_ACC_NB = ACCT_ACC_NB(+)) WHERE TEST_BATCH_DT = (:B1 )Your input is highly appreciated.
    Thanks for taking your time in answering my question.
    Regards

    Oracle Lover3 wrote:
    Dear experts,
    awrsqrpt.sql is showing multiple executions plans for a single SQL statement. How is it possible that one SQL statement will have multiple Executions Plans within the same AWR report.If you're using bind variables and you've histograms on your columns which can be created by default in 10g due to the "SIZE AUTO" default "method_opt" parameter of DBMS_STATS.GATHER__STATS it is quite normal that you get different execution plans for the same SQL statement. Depending on the values passed when the statement is hard parsed (this feature is called "bind variable peeking" and enabled by default since 9i) an execution plan is determined and re-used for all further executions of the same "shared" SQL statement.
    If now your statement ages out of the shared pool or is invalidated due to some DDL or statistics gathering activity it will be re-parsed and again the values passed in that particular moment will determine the execution plan. If you have skewed data distribution and a histogram in place that reflects that skewness you might get different execution plans depending on the actual values used.
    Since this "flip-flop" behaviour can sometimes be counter-productive if you're unlucky and the values used to hard parse the statement leading to a plan that is unsuitable for the majority of values used afterwards, 11g introduced the "adaptive" cursor sharing that attempts to detect such a situation and can automatically re-evaluate the execution plan of the statement.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Capturing log files from multiple .ps1 scripts called from within a .bat file

    I am trying to invoke multiple instances of a powershell script and capture individual log files from each of them. I can start the multiple instances by calling 'start powershell' several times, but am unable to capture logging. If I use 'call powershell'
    I can capture the log files, but the batch file won't continue until that current 'call powershell' has completed.
    ie.  within Test.bat
    start powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > a.log 2>&1
    timeout /t 60
    start powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > b.log 2>&1
    timeout /t 60
    start powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > c.log 2>&1
    timeout /t 60
    start powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > d.log 2>&1
    timeout /t 60
    start powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > e.log 2>&1
    timeout /t 60
    start powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > f.log 2>&1
    the log files get created but are empty.  If I invoke 'call' instead of start I get the log data, but I need them to run in parallel, not sequentially.
    call powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > a.log 2>&1
    timeout /t 60
    call powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > b.log 2>&1
    timeout /t 60
    call powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > c.log 2>&1
    timeout /t 60
    call powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > d.log 2>&1
    timeout /t 60call powershell . \Automation.ps1 %1 %2 %3 %4 %5 %6 > e.log 2>&1
    Any suggestions of how to get this to work?

    Batch files are sequential by design (batch up a bunch of statements and execute them). Call doesn't run in a different process, so when you use it the batch file waits for it to exit. From CALL:
    Calls one batch program from another without stopping the parent batch program
    I was hoping for the documentation to say the batch file waits for CALL to return, but this is as close as it gets.
    Start(.exe), "Starts a separate window to run a specified program or command". The reason it runs in parallel is once it starts the target application start.exe ends and the batch file continues. It has no idea about the powershell.exe process
    that you kicked off. Because of this reason, you can't pipe the output.
    Update: I was wrong, you can totally redirect the output of what you run with start.exe.
    How about instead of running a batch file you run a PowerShell script? You can run script blocks or call individual scripts in parallel with the
    Start-Job cmdlet.
    You can monitor the jobs and when they complete, pipe them to
    Receive-Job to see their output. 
    For example:
    $sb = {
    Write-Output "Hello"
    Sleep -seconds 10
    Write-Output "Goodbye"
    Start-Job -Scriptblock $sb
    Start-Job -Scriptblock $sb
    Here's a script that runs the scriptblock $sb. The script block outputs the text "Hello", waits for 10 seconds, and then outputs the text "Goodbye"
    Then it starts two jobs (in this case I'm running the same script block)
    When you run this you receive this for output:
    PS> $sb = {
    >> Write-Output "Hello"
    >> Sleep -Seconds 10
    >> Write-Output "Goodbye"
    >> }
    >>
    PS> Start-Job -Scriptblock $sb
    Id Name State HasMoreData Location Command
    1 Job1 Running True localhost ...
    PS> Start-Job -Scriptblock $sb
    Id Name State HasMoreData Location Command
    3 Job3 Running True localhost ...
    PS>
    When you run Start-Job it will execute your script or scriptblock in a new process and continue to the next line in the script.
    You can see the jobs with
    Get-Job:
    PS> Get-Job
    Id Name State HasMoreData Location Command
    1 Job1 Running True localhost ...
    3 Job3 Running True localhost ...
    OK, that's great. But we need to know when the job's done. The Job's Status property will tell us this (we're looking for a status of "Completed"), we can build a loop and check:
    $Completed = $false
    while (!$Completed) {
    # get all the jobs that haven't yet completed
    $jobs = Get-Job | where {$_.State.ToString() -ne "Completed"} # if Get-Job doesn't return any jobs (i.e. they are all completed)
    if ($jobs -eq $null) {
    $Completed=$true
    } # otherwise update the screen
    else {
    Write-Output "Waiting for $($jobs.Count) jobs"
    sleep -s 1
    This will output something like this:
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    Waiting for 2 jobs
    When it's done, we can see the jobs have completed:
    PS> Get-Job
    Id Name State HasMoreData Location Command
    1 Job1 Completed True localhost ...
    3 Job3 Completed True localhost ...
    PS>
    Now at this point we could pipe the jobs to Receive-Job:
    PS> Get-Job | Receive-Job
    Hello
    Goodbye
    Hello
    Goodbye
    PS>
    But as you can see it's not obvious which script is which. In your real scripts you could include some identifiers to distinguish them.
    Another way would be to grab the output of each job one at a time:
    foreach ($job in $jobs) {
    $job | Receive-Job
    If you store the output in a variable or save to a log file with Out-File. The trick is matching up the jobs to the output. Something like this may work:
    $a_sb = {
    Write-Output "Hello A"
    Sleep -Seconds 10
    Write-Output "Goodbye A"
    $b_sb = {
    Write-Output "Hello B"
    Sleep -Seconds 5
    Write-Output "Goodbye B"
    $job = Start-Job -Scriptblock $a_sb
    $a_log = $job.Name
    $job = Start-Job -Scriptblock $b_sb
    $b_log = $job.Name
    $Completed = $false
    while (!$Completed) {
    $jobs = Get-Job | where {$_.State.ToString() -ne "Completed"}
    if ($jobs -eq $null) {
    $Completed=$true
    else {
    Write-Output "Waiting for $($jobs.Count) jobs"
    sleep -s 1
    Get-Job | where {$_.Name -eq $a_log} | Receive-Job | Out-File .\a.log
    Get-Job | where {$_.Name -eq $b_log} | Receive-Job | Out-File .\b.log
    If you check out the folder you'll see the log files, and they contain the script contents:
    PS> dir *.log
    Directory: C:\Users\jwarren
    Mode LastWriteTime Length Name
    -a--- 1/15/2014 7:53 PM 42 a.log
    -a--- 1/15/2014 7:53 PM 42 b.log
    PS> Get-Content .\a.log
    Hello A
    Goodbye A
    PS> Get-Content .\b.log
    Hello B
    Goodbye B
    PS>
    The trouble though is you won't get a log file until the job has completed. If you use your log files to monitor progress this may not be suitable.
    Jason Warren
    @jaspnwarren
    jasonwarren.ca
    habaneroconsulting.com/Insights

  • JDBC/select/async statement to JDBC/stored procedure/sync call

    Hi
    We have JDBC/select/async statement to JDBC/stored procedure/sync call i.e sender and receiver are JDBC.
    PI has to pick all the the records of single internal order number at a time from sender system and upload to receiver JDBc,
    gets the response and routes to sender/insert statement.
    This should run only once per day.
    We will have multiple Internal orders daily, each order consisting of 10 to 20 records but only one IO related records has
    to upload to Receiver/JDBC
    What are the options available ?
    We have thought of following options
    1. SQL query is already to pick, but we have to pick records at one time daily. example: morning,evening or midnight.
       At that time it can pick multiple times but it should not pick through out day
    2. Is there any option in BPM so that we can group IO's at a time and upload ? If so what are the steps need to use
       Any additonal receive step need to be used to pick the records from the table.
    Thanks

    hi
    as i can understando you, you will receive mani IO and you must execute one IO in the receiver SP? if so, you can solve this usssing a ccBPM where you will have to create a mapping(0.N) where the source and the target structure will be the same, the diferrence will be in the occurrance of the target structure which will have to be 0.N (Tab signature in Message Mapping). then back to the ccBPM define a block with the property ForEach. this will  loop any times accord with the number of IO that you receive from the sender. as a result you will execute one SP for each IO.
    so, you ccBPM will be
    RS>TS>BLOCK(Multiline container and single container of source structure)>TS->SS
    RS:Receive Step
    TS:Trans. Step
    SS:Send Step
    Also the container will be:
    source--> type Abs
    source_multiline --> type Abs
    target -->type Abs
    Thanks
    Rodrigo P.
    Edited by: Rodrigo Alejandro Pertierra on Jun 24, 2010 4:54 PM

  • Multiple database updates vesus Tansaction

              Hi,
              I need some help from you great minds. Here us what I am trying to accomplish:
              I have a message driven bean which does a multiple update calls to an Oracle database.
              I want to commit all the db updates only at the end (after all update calls execute
              okay) and if there occurs any problem in any of the update calls, I want to rollback
              all the previously successful update calls I have already made. I am using container
              managed transaction via a mdb.
              I tried to use UserTransaciom.setRollbackOnly() call but that did not completely
              help. This call rolled back the message altogether. All I wanted to do is, if
              there occurs any error during a database update, rollback just the database changes
              and just throw away the message. Is there a way I can just rollback the database
              changes? Any suggestions?? please. Thanks
              

    If I understand correctly what you want to do, is the purpose to do some task or run some script in multiple databases on the same server?
    If so, this is done easily by listing the database (sids) in a file and reading the file in a loop statement.
    In my case, I simply create a file on the server called localsids. I keep this in /var/opt/oracle directory.
    Then, in my script, I set:
    SIDFILE='/var/opt/oracle/localsids'
    NEWPASS=`cat $HOME/.xlh/sys`
    # This loop reads through the 'sidlist' and then looks for a password
    # stored in a separate directory for each sid, but if individual
    # directories do not exist, then it uses the standard system password.
    # It then opens a sqlplus session for each sid (as it loops through the
    # sidfile and executes some sql statement(s), or executes a sql script.
    cat $SIDFILE | while read SID
    do
    ORACLE_SID=$SID
    export ORACLE_SID
    echo $SID # this is only for my own verbose purposes
    sqlplus -s system/manager@$SID <<EOF > /tmp/chg_passwd_${SID}.sql
    alter user system identified by $NEWPASS
    alter user sys identified by $NEWPASS
    EOF
    done
    exit
    # In the above example, i am changing the sys and system passwords for all databases listed in the localsids file.
    Hope this helps...
    ji li
    Message was edited by: ji li to simplify the example...
    I have simplified the above example to hardcode the system password into this script, however, normally I would never do this in real practice. This is just as an example to simplify how to run a loop to run a common script or sql statement in each database.

  • Using Spring JDBC with JHeadstart

    We have to migrate a Forms application using JHeadstart.
    But all of the business logic is present in a set of PL/SQL
    code which is required to be reused for the J2EE based forms.
    Therefore, the JHeadstart migrated application needs
    to use the PL/SQL code to display and update data.
    If Spring JDBC has been chosen as the DAO technology
    to create the DTOs, how can we plug this into the JSF
    pages created by JHeadstart?
    Thanks,
    Gurdev

    Gurdev,
    JHeadstart only works on top of ADF Business Components. So if Spring is a given, you cannot use JHeadstart.
    Note that ADF BC provides excellent support to call stored procedures, very similar to how Forms supports blocks based on stored procedures, so if it is still an option you might want to consider using ADF BC instead of Spring, which would open the door for JHeadstart as well.
    While Spring is a great framework (we use it under the covers in JHeadstart as well!), I believe ADF BC is the best fit when migrating forms, since many Forms concepts have been brought forward to ADF BC. For example, check out this link:
    http://www.oracle.com/technology/products/jdev/tips/muench/formstriggers/index.html
    Steven Davelaar,
    Jheadstart Team.

  • Multiple Database Updates

    Hi
    In development environment I have many branches(copies) of a database.
    For every change (ddl, dml) i have to login every database manually to execute statements, Is there a client tool that support multiple database update or if any expert ever make a customized routine for that?
    And ideally as i have different named branches i wish i can define the scope of change too i.e. change execute on databases of "abc" & "pqr" branches only.
    Wishes

    If I understand correctly what you want to do, is the purpose to do some task or run some script in multiple databases on the same server?
    If so, this is done easily by listing the database (sids) in a file and reading the file in a loop statement.
    In my case, I simply create a file on the server called localsids. I keep this in /var/opt/oracle directory.
    Then, in my script, I set:
    SIDFILE='/var/opt/oracle/localsids'
    NEWPASS=`cat $HOME/.xlh/sys`
    # This loop reads through the 'sidlist' and then looks for a password
    # stored in a separate directory for each sid, but if individual
    # directories do not exist, then it uses the standard system password.
    # It then opens a sqlplus session for each sid (as it loops through the
    # sidfile and executes some sql statement(s), or executes a sql script.
    cat $SIDFILE | while read SID
    do
    ORACLE_SID=$SID
    export ORACLE_SID
    echo $SID # this is only for my own verbose purposes
    sqlplus -s system/manager@$SID <<EOF > /tmp/chg_passwd_${SID}.sql
    alter user system identified by $NEWPASS
    alter user sys identified by $NEWPASS
    EOF
    done
    exit
    # In the above example, i am changing the sys and system passwords for all databases listed in the localsids file.
    Hope this helps...
    ji li
    Message was edited by: ji li to simplify the example...
    I have simplified the above example to hardcode the system password into this script, however, normally I would never do this in real practice. This is just as an example to simplify how to run a loop to run a common script or sql statement in each database.

  • Multiple Rows Update / Refresh Toplink Query when database trigger involved

    Hi everybody!
    I have two easy troubles for you; the platform is the same as the SRDemo Toplink version.
    1.     Multiple Rows Update: I want to update with mergeEntity method, multiple rows for an isolated table; that method receives a parameter that I try to bind with the iterator "dataProvider" but it only merges the first row, not all, any other combination returns an error.
    What I want to do is to have a form (like tabular forms in Apex) that lets me update multiple rows in a single page. ¿May anyone tell me how to do it?
    2.     Refresh Toplink Named Query: I have a list on a page with two columns. From another page, a button does an action that fires a database trigger that updates one of the columns on the list´s page. When I go back to the list, it is not updated; however, the CacheResults´s property is set to false on the iterator.
    Thanks in advance,
    Alejandro T

    I didn't use it (yet), but - you might take a look. You'll find a [url http://www.oracle.com/technetwork/developer-tools/apex/application-express/apex-plug-ins-182042.html]Timer plug-in on this page. It is a dynamic action which allows you to periodically fire other dynamic actions in the browser. For example use the timer to refresh a region every five minutes. You can perform any dynamic action you want using this infrastructure.So I was thinking: you might use it to run a dynamic action which would check whether something changed in that table (I suppose you'll know the way) (for example, a database trigger might set a flag in some table, timestamp or similar), and - if you find that something really changed - refresh the page.
    As I said, I never used it so that's pure theory. Someone else might know better, though.

Maybe you are looking for