配置JNDI數據源


一、JBoss配置數據源 
在JBoss的 D:\jboss420GA\docs\examples\jca 文件夾下面,有不少不一樣數據庫引用的數據源定義模板。將其中的 mysql-ds.xml 文件Copy到你使用的服務器下,如 D:\jboss420GA\server\default\deploy。 
修改 mysql-ds.xml 文件的內容,以下: 
java

<?xml version="1.0" encoding="UTF-8"?> 
<datasources> 
<local-tx-datasource> 
    <jndi-name>MySqlDS</jndi-name> 
    <connection-url>jdbc:mysql://localhost:3306/lw</connection-url> 
    <driver-class>com.mysql.jdbc.Driver</driver-class> 
    <user-name>root</user-name> 
    <password>rootpassword</password> 
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name> 
    <metadata> 
       <type-mapping>mySQL</type-mapping> 
    </metadata> 
</local-tx-datasource> 
</datasources>

二、Tomcat配置數據源  
1)(全局配置)在tomcat的conf文件夾下的context.xml配置文件中加入:mysql

<Resource name="jndi/mybatis" 
    auth="Container" 
    type="javax.sql.DataSource" 
    driverClassName="com.mysql.jdbc.Driver" 
    url="jdbc:mysql://localhost:3306/appdb" 
    username="root" 
    password="123456" 
    maxActive="20" 
    maxIdle="10" 
    maxWait="10000"/>

而後在項目的web.xml中加入資源引用:web

<resource-ref>
  <description>JNDI DataSource</description>
  <res-ref-name>jndi/mybatis</res-ref-name>
  <res-ref-type>javax.sql.DataSource</res-ref-type>
  <res-auth>Container</res-auth>
</resource-ref>

其中res-ref-name值要和context.xml的name值一致。
sql

2)在項目的META-INF下面新建context.xml。加入:數據庫

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jndi/mybatis" 
        auth="Container" 
        type="javax.sql.DataSource" 
        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/appdb" 
        username="root" 
        password="123456" 
        maxActive="20" 
        maxIdle="10" 
        maxWait="10000"/>
</Context>

其餘配置同第一種方式。
tomcat

在項目的web.xml中添加的資源引用無關緊要。服務器

三、在程序中引用數據源: 

mybatis

Connection conn=null; 
try 
{ 
    Context ctx=new InitialContext(); 
    Object datasourceRef=ctx.lookup("java:MySqlDS"); 
    //引用數據源 
    DataSource ds=(Datasource)datasourceRef; 
    conn=ds.getConnection(); 
    /* 使用conn進行數據庫SQL操做 */ 
    conn.close(); 
}catch(Exception e){
    e.printStackTrace();
}finally {
  
} 
JNDI避免了程序與數據庫之間的緊耦合,使應用更加易於配置、易於部署。
相關文章
相關標籤/搜索