What is datasource?
The DataSource interface provides an alternative to the DriverManager for making a connection.
It makes the code more portable than DriverManager because it works with JNDI and it is created, deployed and managed separately from the application that uses it. If the DataSource location changes, then there is no need to change the code but change the configuration properties in the server. This makes your application code easier to maintain.
It also allows the use of connection pooling and support for distributed transactions.
A DataSource is not only a database but also can be a file or a spreadsheet.
A DataSource object can be bound to JNDI and an application can retrieve and use it to make a connection to the database. J2EE application servers provide tools to define your DataSource with a JNDI name.
When the server starts it loads all the DataSources into the application server’s JNDI service.
DataSource configuration properties are shown below:
- JNDI Name - jdbc/myDataSource
- URL – jdbc:oracle:thin:@hostname:1526:myDB
- UserName, Password
- Implementation classname – oracle.jdbc.pool.OracleConnectionPoolDataSource
- Classpath – ora_jdbc.jar
- Connection pooling settings like – minimum pool size, maximum pool size, connection timeout, statement cache size etc.
Once the DataSource has been set up, then you can get the connection object as follows:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/tsDataSource");
Connection myConnection = ds.getConnection(“username”,”password”);