您的位置:首页 > 数据库 > Oracle

eclipse中tomcat配置JNDI链接Oracle数据源例子

2015-06-18 14:38 330 查看
  最近换到新公司,第一次接触JNDI方式连接数据库。

  一开始怎么找也没找到数据库地址在哪里配置的,后面跟代码发现spring中初始化dataSource是通过这个类JndiObjectFactoryBean传入jndiName参数,果断百度JndiObjectFactoryBean才知道有JNDI这种方式获取dataSource。

  由于项目是分布式的(统一使用Jboss),如果想分开部署配置Jboss端口太麻烦,so 想用tomcat来代替。jboss配置JNDI比较简单,这里不讲。eclipse新建一个tomcat服务会自动建一个Servers工程,里面包含了context.xml、server.xml等配置文件,tomcat配置就需要注意不要配置tomcat所在目录的配置文件,而是需要配置这里的配置文件

配置配置方法如下:

一、在Servers工程下面的context.xml文件当添加以下的配置信息:
<Context>

<Resource name="jdbc/test" auth="Container"
type="javax.sql.DataSource"
username="sean"
password="sean"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
maxActive="100"
maxIdle="30"
maxWait="10000"/>

</Context>

二、在Servers工程下面的web.xml配置

<resource-ref>
<description>OracleDataSource</description>

<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

三、spring获取dataSource

<!-- 报表数据访问方式修改为jndi的方式 -->
<bean id="dataSource" name="default_ds" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/test" />
<property name="resourceRef" value="true" />
</bean>

四、使用数据源连接数据库
private Connection getConnection() throws NamingException {
Connection conn = null;
String jndi = "jdbc/test";
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup(jndi);
if(ds != null){
try {
conn = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}

return conn;
}

public List<String> selectById(int id) throws InstantiationException, IllegalAccessException{
Connection con = null;
try {
con = getConnection();
} catch (NamingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
List<String> list = new ArrayList<String>();
String sql="select * from myusers where id=?";
try {
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: