Java more than one DB connection in UserTransaction

前端 未结 5 838
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 23:12
static void clean() throws Exception {
  final UserTransaction tx = InitialContext.doLookup(\"UserTransaction\");
  tx.begin();

  try {
    final DataSource ds = In         


        
5条回答
  •  清歌不尽
    2021-01-19 23:50

    Since your application is running in weblogic server, the java-EE-container is managing the transaction and the connection for you. If you call DataSource#getConnection multiple times in a java-ee transaction, you will get multiple Connection instances joining the same transaction. Usually those connections connect to database with the identical session. Using oracle you can check that with the following snippet in a @Stateless ejb:

    @Resource(lookup="jdbc/myDS")
    private DataSource ds;
    
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    @Schedule(hour="*", minute="*", second="42")
    public void testDatasource() throws SQLException {
    
        try ( Connection con1 = ds.getConnection();
              Connection con2 = ds.getConnection();
            ) {
    
            String sessId1 = null, sessId2 = null;
            try (ResultSet rs1 = con1.createStatement().executeQuery("select userenv('SESSIONID') from dual") ){
                if ( rs1.next() ) sessId1 = rs1.getString(1);
            };
            try (ResultSet rs2 = con2.createStatement().executeQuery("select userenv('SESSIONID') from dual") ){
                if ( rs2.next() ) sessId2 = rs2.getString(1);
            };
    
            LOG.log( Level.INFO," con1={0}, con2={1}, sessId1={2}, sessId2={3}"
                   , new Object[]{ con1, con2, sessId1, sessId2}
                   );
        }
    
    }
    

    This results in the following log-Message:

    con1=com.sun.gjc.spi.jdbc40.ConnectionWrapper40@19f32aa, 
    con2=com.sun.gjc.spi.jdbc40.ConnectionWrapper40@1cb42e0, 
    sessId1=9347407, 
    sessId2=9347407
    

    Note that you get different Connection instances with same session-ID.

    For more details see eg this question

提交回复
热议问题