【发布时间】:2012-02-29 05:27:56
【问题描述】:
我正在尝试创建一个 BMT EJB 示例并手动控制事务,但是当尝试运行时,我得到了 NullException,我不知道我做错了什么。 代码如下:
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
@Local(GlobalTLocal.class)
public class GlobalT implements GlobalTLocal {
@Resource
private UserTransaction utx;
public GlobalT() {
}
@Override
public void sincroniza() {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
String sqlPostgres = "SELECT * FROM RH.RHINFORMIX";
String insert = "INSERT INTO RH.RHINFORMIX (id_agente,fk_codigo_area,nome,email,excluido,tipoinclusao,id,teste)"+
" VALUES (11,11,'teste','teste',false,'I',12,'teste')";
InitialContext ic = new InitialContext(env);
DataSource ds = (DataSource) ic.lookup("jdbc/RHMigracaoPostgres");
con = ds.getConnection();
utx.begin();
// con.setAutoCommit(false);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlPostgres);
while (rs.next()) {
System.out.println("Query '" + sqlPostgres + "' returned "
+ rs.getString(3));
}
stmt.executeUpdate(insert);
// con.commit();
// if(true){
// throw new Exception();
// }
utx.commit();
} catch (Exception e) {
try {
utx.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally{
if(rs != null)
try {
rs.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
当我运行这个类时,我收到以下错误:
java.lang.NullPointerException
at br.gov.dprf.GlobalT.sincroniza(GlobalT.java:94)
at Principal.main(Principal.java:11)
java.lang.NullPointerException
at br.gov.dprf.GlobalT.sincroniza(GlobalT.java:71)
at Principal.main(Principal.java:11)
这个EJB部署在一个Jboss 4.2.2的服务器上,在Jboss启动过程中没有错误,我们可以看到部署的EJB的日志:
15:51:33,529 INFO [EJB3Deployer] Deployed: file:/C:/Jboss-Limpos/jboss-4.2.2.GA/server/all/deploy/GlobalTransaction.jar
我正在尝试强制 UserTransaction 为我提交插入!!!
我做错了什么?
Tks
【问题讨论】:
-
堆栈跟踪中的行号与您的代码不匹配。第 71 行和第 94 行在做什么?看来您正在使用 JavaSE 直接启动 Principal 类:这行不通;注入仅支持 EE 组件。您需要从 JNDI 中查找您的 EJB,或者在应用程序客户端容器中使用注入。
-
抱歉来晚了。第 71 和 94 行是“utx.begin();”和“utx.rollback();”。就像你说的那样,我正在发射。你能给我举例说明如何做你的建议吗? GlobalT 类位于 Jboss 容器内的部署文件夹中。 Jboss 上线后,我运行创建 GlobalT 实例并调用 sincroniza 方法的 Principal 类。
标签: java transactions jboss ejb jta