我正在尝试从 CDI bean 访问 Oracle 数据源。
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
import javax.sql.DataSource;
@Named("ParentIDNameResolveController")
@ViewScoped
public class ParentIDNameResolve implements Serializable
{
// Call the Oracle JDBC Connection driver
@Resource(name = "jdbc/Oracle")
private static DataSource ds;
// Get the ID if the parent
public static int ParentId(int chieldId) throws SQLException
{
int ParentId = 0;
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
try
{
conn = ds.getConnection();
ps = conn.prepareStatement("SELECT COMPONENTID, FKCOMPONENTID, COMPONENTSTATSID from COMPONENT where COMPONENTID = ?");
ps.setLong(1, chieldId);
rs = ps.executeQuery();
while (rs.next())
{
ParentId = rs.getInt("FKCOMPONENTID");
}
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
return ParentId;
}
// Get Parent Name
public static String ParentName(int ParentId) throws SQLException
{
String ParentName = null;
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
try
{
conn = ds.getConnection();
ps = conn.prepareStatement("SELECT COMPONENTSTATSID, NAME from COMPONENTSTATS where COMPONENTSTATSID = ?");
ps.setLong(1, ParentId);
rs = ps.executeQuery();
while (rs.next())
{
ParentName = rs.getString("NAME");
}
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
return ParentName;
}
}
不幸的是,当我从静态 Java 方法引用数据源时,我得到了这个错误:
Can't get data source
我不确定是否可以从静态 Java 方法访问数据源。有没有办法解决这个问题?