DataSource and DriverManager are the two basic ways to connect to a database in a JEE application.
The DriverManager is older facility, the DataSource is newer.
It is recommended to use the new DataSource facility to connect to databases and other resources.
DriverManager will take time as it creates the connection whenever you require.
It involves loading the driver class and registering the driver. then it will creates the connection.
Class.forName("com.mysql.jdbc.Driver");
Connection myConnection = DriverManager.getConnection(prop.getProperty("DataBaseUrl"),prop.getProperty("user"),prop.getProperty("password"));
Using DataSource you can get connection from connection pool. High trafic enterprise applications need
fine tuned connection pools. you can implement Apache Commons DBCP, or C3P0 Connection pools.
C3P0 additionally pool statements also, apart from connection pool.
BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource();
((BasicDataSource) dataSource).setDriverClassName(prop.getProperty("driverClassName"));
((BasicDataSource) dataSource).setUrl(prop.getProperty("keyClockUrl"));
((BasicDataSource) dataSource).setUsername(prop.getProperty("user"));
((BasicDataSource) dataSource).setPassword(prop.getProperty("password"));
((BasicDataSource) dataSource).setMaxActive(Integer.valueOf(prop.getProperty("initialSize")));
((BasicDataSource) dataSource).setMaxActive(Integer.valueOf(prop.getProperty("minIdle")));
((BasicDataSource) dataSource).setMaxActive(Integer.valueOf(prop.getProperty("maxActive")));
((BasicDataSource) dataSource).setMaxIdle(Integer.valueOf(prop.getProperty("maxIdle")));
((BasicDataSource) dataSource).setMaxWait(Integer.valueOf(prop.getProperty("maxWait")));
((BasicDataSource) dataSource).setDefaultAutoCommit(Boolean.getBoolean(prop.getProperty("defaultAutoCommit")));
((BasicDataSource) dataSource).setDefaultReadOnly(Boolean.getBoolean(prop.getProperty("defaultReadOnly")));
myConnection = dataSource.getConnection();
private static ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://111.xx.xxx.xxx:3306/clock_db");
cpds.setUser("xxxxx");
cpds.setPassword("xxxxxx");
cpds.setInitialPoolSize(15);
cpds.setMinPoolSize(25);
cpds.setMaxPoolSize(50);
cpds.setMaxStatements(15);
cpds.setAcquireRetryAttempts(2);
cpds.setPrivilegeSpawnedThreads(true);
cpds.setContextClassLoaderSource("library");
cpds.setTestConnectionOnCheckin(true);
cpds.setTestConnectionOnCheckout(false);
cpds.setMaxConnectionAge(30);
if (cpds.getNumBusyConnectionsAllUsers() >= cpds.getMaxPoolSize()) {
//hardReset() immediately closes all Connections managed by the DataSource, including those that are currently checked out,
//bringing the DataSource back to the state it was in before the first client called getConnection().
//cpds.hardReset();
System.out.println("SOFT RESET CP");
// Connections aren't close()ed
cpds.softResetAllUsers();
}
//create connection and do the stuff
Connection myConnection = C3poDataSource.getConnection();
After this question is raised we will get 2 questions in mind?
What is connection pooling ?
What is instance pooling ?
Why should we go for instance pooling ?
Creation of Database Connection is an expensive task?
First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC? application connects to a target data source using one of two mechanisms:
DriverManager
: This fully implemented class
requires an application to load a specific driver, using a hardcoded
URL. As part of its initialization, the DriverManager
class attempts to load the driver classes referenced in the jdbc.drivers
system property. This allows you to customize the JDBC Drivers used by your applications. DataSource
: This interface is preferred over DriverManager
because it allows details about the
underlying data source to be transparent to your application. A DataSource
object's properties are set so that it represents a particular data source.Establishing a connection involves two steps: Loading the driver, and making the connection.
DataSource
object increases application portability by making it possible for an
application to use a logical name for a data source instead of having
to supply information specific to a particular driver. The following
example shows how to use a DataSource
to establish a connection:
You can configure a DataSource
using a tool or manually. For example, Here is an example of a DataSource
lookup:
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection();
DataSource
implementations must provide getter and setter methods for each
property they support. These properties typically are initialized when the
DataSource
object is deployed.
VendorDataSource vds = new VendorDataSource();
vds.setServerName("my_database_server");
String name = vds.getServerName();
Connection Pooling in Struts :
In struts-config.xml file data sources tag is there? you can configure connection pool from that xml file and you can create the connection as below.
<data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="url" value="jdbc:mysql://localhost/DBNAME" />
<set-property property="username" value="" />
<set-property property="password" value="abcdefgh" />
<set-property property="maxActive" value="20" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="false" />
<set-property property="defaultReadOnly" value="false" />
data-source>
data-sources>
...//Here Other Struts Configuration Tags...
struts-config >
In the above file the default values comes with this file was maxActive 20.
You can set the values here as per your network traffic on your server?
Here totally 20 connection objects will be active in the pool and 5000 (5 seconds ) will be the time to wait for a connection object. You can set number of maxIdle connections also.
CODE : in your Action Class execute method or any other class you can create the connection object like this.
//Just declare the data source and connection objects;
javax.sql.DataSource dataSource = null;
java.sql.Connection myConnection = null;
//Just by using the following 2 lines of Code you can create a connection //object from the data source by using the concept of connection pooling.
dataSource = getDataSource(request);
myConnection = dataSource.getConnection();
You can also refer to EJB Instance Pooling...
How do you configure data source in Tomcat ?
How do you configure data source in WebLogic ?
How do you configure data source in JBoss ?
How do you configure data source in WebSphere ?
If we want a database connection from the pool, we need to create it from the DataSource not from DriverManager.
So DriverManager.getConnection() method will give you normal connection Where as DataSource.getConnection() method will give you a database connection from the connection pool.
To get a DataSource reference we need a JNDI name, from that name we can get InitialContext reference.
The following is the Standard code to get a connection from DataSource. For more information refer to WebLogic Docs.
The JNDI name will be there in the Directory Service. The Initial Context Object will get the information from the Directory Service.
InitalContext ic = new InitialContext();
Hashtable ht = new Hashtable();
ht.put( Context.INITIAL_CONTEXT_FACTORY,weblogic.jndi.WLInitialContextFactory);
//You have to set weblogic properties first and the JNDI name that you are defining in Weblogic while creating the connection pool
//here t3 means TENGA Protocol
ht.put( Context.PROVIDER_URL t3://localhost:7001);
ht.put( Context.SECURITY_PRINCIPAL username);
ht.put( Context.SECURITY_CREDENTIALS password_of_ weblogic);
Whenever you need a connection in your Java Class you can use the following lines of code.
DataSource ds = (DataSource)ic.lookup("jndiname");
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
//from here you can play normally
<
beanid="dataSource"
class
="org.apache.commons.dbcp.BasicDataSource">
<
propertyname="driver">
${db.driver}
<
propertyname="url">
${db.url}
<
propertyname="username">
${db.username}
<
propertyname="password">
${db.password}
<
beanid="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<
propertyname="jndiName">
java:comp/env/jdbc/myDatasource
With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database.
JdbcTemplate template = new JdbcTemplate(myDataSource);
A simple DAO class looks like this.
public
classStudentDaoJdbc
implements StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
more..
}
The configuration is shown below.
<
beanid="jdbcTemplate"
class
="org.springframework.jdbc.core.JdbcTemplate">
<
propertyname="dataSource">
<ref
bean="dataSource"/>
</property>
</bean>
<
beanid="studentDao"
class="StudentDaoJdbc">
<
propertyname="jdbcTemplate">
<ref
bean="jdbcTemplate"/>
</property>
</bean>
<
beanid="courseDao"
class="CourseDaoJdbc">
<
propertyname="jdbcTemplate">
<ref
bean="jdbcTemplate"/>
</property>
</bean>
Ads By Google
© 2018 - JavaSpartans.com • All Rights Reserved