Archive

Posts Tagged ‘JNDI’

Accessing databases using datasource xml

March 15, 2010 Leave a comment

We will use the previous struts project to setup database access to MySQL running on localhost.
Run the following command to create the .project and .classpath files for Eclipse and import the project in Eclipse

mvn eclipse:m2eclipse

Download the database driver mysql-connector-java-5.1.11-bin.jar from here and save it to the lib folder in this location $JBOSS_HOME/server/web/lib

Create a jboss-web.xml file in the WEB-INF folder with the following content

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
 <resource-ref>
 <res-ref-name>CodesiloDS</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <jndi-name>java:CodesiloDS</jndi-name>
 </resource-ref>
</jboss-web>

In the web.xml file add the following :

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

Create a datasource xml file and add it to the deploy dir of JBoss.

Here is the content of my file:

<datasources>
 <local-tx-datasource>
 <jndi-name>CodesiloDS</jndi-name>
 <connection-url>jdbc:mysql://localhost:3306/database-name</connection-url>
 <driver-class>com.mysql.jdbc.Driver</driver-class>
 <user-name>username</user-name>
 <password>password</password>
 <min-pool-size>5</min-pool-size>
 <max-pool-size>20</max-pool-size>
 <!-- Typemapping for JBoss 4.0 -->
 <metadata>
 <type-mapping>mySQL</type-mapping>
 </metadata>
 </local-tx-datasource>
</datasources>

Replace database-name, username and password with appropriate values.

To keep things simple to test, we will add an action in struts-config and have the Action class call the database.

In the action class add this

private final String DATABASE_JNDI_SOURCE = "java:CodesiloDS";

and have this in the execute method. (In the real world most of this code would reside in your model and any helper classes.)

public ActionForward execute(ActionMapping mapping, ActionForm form,
 HttpServletRequest request, HttpServletResponse response)
 throws Exception {

 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 String date ="";
 try{
 Context ctx = new InitialContext();
 DataSource ds = (DataSource)ctx.lookup(DATABASE_JNDI_SOURCE);
 if(ds!= null){
 conn = ds.getConnection();
 stmt = conn.createStatement();
 rs = stmt.executeQuery("select curdate() from dual;");
 if(rs.next()){
 date = rs.getString(1);
 }
 }
 }
 catch(Exception e){
 ---- code here----
 }
 finally{
 try{
 rs.close();
 stmt.close();
 conn.close();
 }
 catch(Exception e){
 ---- code here -----
 }
 }
 System.out.println("This is a test: " + date);
 return mapping.findForward("success");
 }

Once we call the action, we should see the current date printed on the console.