Basics of DataSource :

Datasource is a name given to the connection set up to a database from a server . DataSource is an alternative to DriverManager for getting the connection . 
We should prefer database connections getting from  a DataSource instead of a DriverManager.
Using a Datasource you need to know only the JNDI name. The JNDI style is typical when using an application server or a web container

Java Example for configuring and accessing a DataSource:
--------------------------------------------------------
1) Configure the JNDI DataSource in Tomcat by adding a declaration for your resource to your Context in server.xml  

<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>
   
  
  
2) Now add below lines in web.xml .


<resource-ref>
 <description>Oracle Datasource example</description>
  <res-ref-name>jdbc/myoracle</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>


3) Code example :
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();


Now when we have learnt about what a DataSource is and how to configure and access it .Do we really care about what are the benefits of DataSource over traditional DriverManager approach ??

DataSource provides us with connection pooling feature , better scalability and maintainence.
For driver manager you need to know all the details (host, port, username, password, driver class) to connect to DB an to get connections. Externalizing those in a properties file doesn't change anything about the fact that you need to know them.

Using a Datasource you need to know only the JNDI name. The Appserver cares about the details and is not configured by the client application' vendor but by an admin where the application is hosted.

JNDI really shines when you have to move an application between environments: development to integration to test to production. If you configure each app server to use the same JNDI name, you can have different databases in each environment and not have to change your code. You just pick up the WAR file and drop it in the new environment.



Brother website for healthcare : http://delighthealthcare.in/


Comments

Popular posts from this blog

Arrays.sort() and Collections.sort() NullPointerException

org.xml.sax. SAXParseException: Element type "web-app" must be declared.

Sentimental Analysis : PART 1