views:

932

answers:

3

I've always used Spring's dependency injection to get datasource objects and use them in my DAOs, but now, I have to write an app without that.

With Spring I can write something like this:

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://127.0.0.1/app?characterEncoding=UTF-8" />
    <property name="username" value="u" />
    <property name="password" value="p" />
</bean>

But how can I use datasource in my DAOs without Spring or anything? I'm using servlets and JSPs only. Performance is very important factor.

A: 

You can declare your data source as a JNDI object and retrieve a datasource via a JNDI lookup:

DataSource ds = (DataSource)
  envCtx.lookup("jdbc/EmployeeDB");

as documented here and here.

That's as bare-bones as you can get, so from there on, performance is completely up to you.

Tomislav Nakic-Alfirevic
Thanks for this, too.
Bob
You're welcome. :)
Tomislav Nakic-Alfirevic
+1  A: 

Believe it or not, people were writing applications before Spring and some are still not using it :) In your case, you could use Tomcat connection pool (and there is a complete configuration example for MySQL in the documentation). Let me summarize it:

First, put your driver in $CATALINA_HOME/lib.

Then, configure a JNDI DataSource in Tomcat by adding a declaration for your resource to your Context:

<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

    <!-- maxActive: Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to -1 for no limit.
         -->

    <!-- maxIdle: Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->

    <!-- maxWait: Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->

    <!-- username and password: MySQL dB username and password for dB connections  -->

    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
         -->

    <!-- url: The JDBC connection url for connecting to your MySQL dB.
         -->

  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest"/>

</Context>

Declare this resource in your web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

And get the datasource with a JNDI lookup in your application:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

Note that such lookup is usually coded in a ServiceLocator (when you can't have a a DI container or a framework inject it for you).

Pascal Thivent
Thanks a lot! I'll try it.
Bob
It's beyond me why this didn't have at least a single upvote.
BalusC
@BalusC: Damn, I'll never get that Unsung Hero badge! Just kidding of course, thank you very much.
Pascal Thivent
Lol. You've got to have a [long journey](http://odata.stackexchange.com/stackoverflow/s/345/how-unsung-am-i).
BalusC
@BalusC If that ever happens, I quit!
Pascal Thivent
A: 

Pascal, I tried your advice, also found at http://tomcat.apache.org/tomcat-4.1-doc/jndi-datasource-examples-howto.html

I've followed the given instructions, but I'm facing the problem: "org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: com.tonbeller.jpivot.olap.model.OlapException: Could not load Jdbc Driver com.mysql.jdbc.Driver" The stack trace is too big, so I think this may suffice. I'm using Tomcat6, on Debian, DB is MySQL. Please help.

Prashant
Welcome at Stackoverflow! The box at bottom states *Your Answer* and has a button called `Post Your Answer`, but the message which you posted isn't an answer at all.. This is a question! Please press the `Ask Question` button at right top to ask a question. Also please be so kind to delete this "answer" by clicking the `delete` link (once you've registered yourself).
BalusC