• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JDBC and Session

 
Hardik Patel p
Ranch Hand
Posts: 40
Hibernate Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

why we are not creating connection instance by using new keyword ?

Connection connection =
DriverManager.getConnection(oracleURL, username, password);

same way in the following

HttpSession session = request.getSession();


Thank you
Hardik
 
Tim Holloway
Saloon Keeper
Posts: 18367
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is more of a basic Java question than a J2EE question. And, for that matter, we don't encourage use of this kind of code in JSPs, anyway, so this probably wasn't the best forum to ask in.

Java has 2 basic ways to construct/obtain resources.

One is the "new" operator. This operator requests that the JVM should instantiate an object by constructing an instance of a class object and invoking any constructor code it may contain.

The other is the Factory design pattern. Using this technique, you don't use "new" because the actual instantiation of the object is done behind the fa├žade of the factory class or object.

Why use a factory? A factory allows the construction process to reference external context as part of the instantiation. That keeps the constructor methods from having to possibly have 157 parameters and isolates them from the need to radically refactor them in the event of wide-ranging changes to the application.

A factory also allows the use of resource pools. You're using the factory method DriverManager.getConnection, which parses the URL to determine what actual driver you need a connection for (Oracle, in this case). You can thus select a different database (say, PostgreSQL) merely by changing the JDBC URL without changing any actual code.

However, in a webapp, getConnection is bad practice. The recommended method is to use a Connection Pool, which is defined to the server, located via JNDI, and then tapped to obtain Connections as needed, Connection pools are preferable in multi-user applications because the process of actually constructing a Connection instance is slow and resource-intensive, whereas keeping a pool of them already made is much, much faster.

The HttpSession factory is a little different. Unlike DriverManager, where a single class is the factory for all Connections, a HttpServletRequest instance actually stores the assiciated HttpSession object within its internal structure. Only in the event that you've requested a session and none exists (AND the "create session" option has been specified) would the HttpServletRequest manufacture and cache a new HttpSession object.
 
Hardik Patel p
Ranch Hand
Posts: 40
Hibernate Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Mr.Tim Holloway
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic