初次使用無狀態sessionbean的問題

flai發表於2007-02-02
無狀態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(****區別之處****)

相關文章