初次使用无状态sessionbean的问题

07-02-02 flai
无状态sessionbean的方法test()中,两次从Datasource取连接,

如果前一连接在取得之后,什么也不做便关闭,则后一连接的AutoCommit()值为true;

如果前一连接有做查询的话,为什么后一连接的AutoCommit值会为false??

(注:此sessionbean的事务设置为容器管理)

如果将此方法放到普通的javabean里来实现,则方法中取得的两次连接的AutoCommit()值均为true,

请问这是为什么??

测试代码如下:

测试一:

public void test() throws SQLException, Exception {

System.out.println("test1");

Context ictx1 = new InitialContext();

DataSource ds1 = (DataSource) ictx1.lookup("JNDI/SIDB");

Connection conn1=ds1.getConnection();

System.out.println("conn1.getAutoCommit()="+conn1.getAutoCommit());

conn1.close();

Context ictx2 = new InitialContext();

DataSource ds2 = (DataSource) ictx2.lookup("JNDI/SIDB");

Connection conn2=ds2.getConnection();

System.out.println("conn2.getAutoCommit()="+conn2.getAutoCommit());

conn2.close();

}

运行结果:

[07-2-1 11:00:48:969 CST] 462c89fd SystemOut O test1

[07-2-1 10:58:53:203 CST] 896c9e5 SystemOut O conn1.getAutoCommit()=true

[07-2-1 10:58:53:219 CST] 896c9e5 SystemOut O conn2.getAutoCommit()=true

测试二:

public void test() throws SQLException, Exception {

System.out.println("test2");

Context ictx1 = new InitialContext();

DataSource ds1 = (DataSource) ictx1.lookup("JNDI/SIDB");

Connection conn1=ds1.getConnection();

System.out.println("conn1.getAutoCommit()="+conn1.getAutoCommit());

PreparedStatement pstmt=conn1.prepareStatement("select * from sysuser");

ResultSet rs=pstmt.executeQuery();

rs.close();

pstmt.close();

conn1.close();

Context ictx2 = new InitialContext();

DataSource ds2 = (DataSource) ictx2.lookup("JNDI/SIDB");

Connection conn2=ds2.getConnection();

System.out.println("conn2.getAutoCommit()="+conn2.getAutoCommit());

conn2.close();

}

运行结果:

[07-2-1 11:00:48:969 CST] 462c89fd SystemOut O test2

[07-2-1 11:00:48:969 CST] 462c89fd SystemOut O conn1.getAutoCommit()=true

[07-2-1 11:00:48:984 CST] 462c89fd SystemOut O conn2.getAutoCommit()=false(****区别之处****)

猜你喜欢