根据 EJB 3.0 规范:当实例处于事务中时,该实例不得尝试使用资源管理器特定的事务划分 API(例如,它不得调用 java.sql.Connection 接口或javax.jms.Session 接口)在规范的 13.3.3 中。我尝试了一个示例 - 在 BEAN 托管事务中我包含 java.sql.Connection.commit() - 在 NetBeans 中创建无状态 bean 作为 EE5,部署在 Glassfish 3.1 上并且容器没有抱怨?Bean 方法更新数据库,在 Glassfish 日志中没有任何错误。这是预期的行为吗?
此外,对于具有规范中提到的容器事务管理事务的 bean,使用 java.sql.Connection.commit() 没有这样的限制。谢谢布拉尼斯拉夫
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ejb;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.Transient;
import javax.sql.DataSource;
import javax.transaction.*;
/**
*
* @author bane
*/
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MySession implements MySessionRemote {
@Resource(name = "SAMPLE")
private DataSource SAMPLE;
//
@Resource UserTransaction utx;
//gore je novi kod
@Override
public String getResult() {
return "This is my Session Bean";
}
public void doSomething() {
try {
Connection conn = SAMPLE.getConnection();
Statement stmt = conn.createStatement();
String q = "select * from BOOK";
String up = "update BOOK set PRICE = PRICE + 1";
utx.begin();
int num = stmt.executeUpdate(up);
System.out.println("num: "+num);
ResultSet rs = stmt.executeQuery(q);
//is conn.commit() legal?
conn.commit();
String name = null;
int price = 0;
while (rs.next()) {
name = rs.getString(2);
price = rs.getInt(3);
System.err.println(name+" , "+price);
}
utx.commit();
} catch (SQLException ex) {
Logger.getLogger(MySession.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(MySession.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}