准备工作
安装JBoss 3.x和MS SQL Server 2000 下载Microsoft SQL Server 2000 Driver for JDBC
开始整合
1. 安装好Microsoft SQL Server 2000 Driver for JDBC后,在其安装目录\lib 下有三个包:msbase.jar、mssqlserver.jar、msutil.jar。把他们拷贝到%JBoss安装目录%\server\default\lib下
2. 将Jboss目录下的docs\examples\jca\中的mssql-ds.xml和mssql-xa-ds.xml拷贝到\server\default\deploy\目录下,并做相应修改(红色部分):
mssql-ds.xml:
<datasources>
<local-tx-datasource>
<jndi-name>MSSQLDS</jndi-name>
<connection-url>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind</connection-url>
<driver-class>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver-class>
<user-name>sa</user-name>
<password></password>
</local-tx-datasource>
</datasources>
mssql-xa-ds.xml:
<datasources>
<xa-datasource>
<jndi-name>MSSQLXADS</jndi-name>
<xa-datasource-class>com.microsoft.jdbcx.sqlserver.SQLServerDataSource</xa-datasource-class>
<xa-datasource-property name="ServerName">localhost</xa-datasource-property>
<xa-datasource-property name="DatabaseName">Northwind</xa-datasource-property>
<xa-datasource-property name="SelectMethod">cursor</xa-datasource-property>
<!-- not sure if these should be here-->
<user-name>sa</user-name>
<password/>
</xa-datasource>
</datasources>
整合测试
1. 编写SessionBean,在其中添加如下方法:
public String testDS() {
String resl = null;
try {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
Context ctx = new InitialContext(p);
resl += "testing the database...\n";
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("java:/MSSQLDS");
//这个”MSSQLDS”必须和mssql-ds.xml文件中的jndi-name保持一致,否则会出错
java.sql.Connection conn =null;
java.sql.Statement st=null;
java.sql.ResultSet rs=null;
try {
conn = ds.getConnection();
st = conn.createStatement();
String sqlStr = "select * from Employees";
rs = st.executeQuery(sqlStr);
while (rs.next()) {
resl += rs.getString("FirstName") + " " +rs.getString("LastName")+"\n";
}
} catch (Exception e) {
}
finally {
if(rs!=null) rs.close();
if(st!=null) st.close();
if(conn!=null) conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return resl;
}
2. 部署EJB
3. 测试SessionBean
public class test{
public void run() {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
try {
Context ctx = new InitialContext(p);
Object obj = ctx.lookup("testBean");
testHome home = (testHome) PortableRemoteObject.narrow(obj, testHome.class);
test t = home.create();
System.out.println("test...");
String str = t.testDS();
System.out.println("received: \n" + str);
System.out.println("test finished!\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new test().run();
}
}
本文地址:http://com.8s8s.com/it/it32369.htm