Connect to the database using JNDI

Source: Internet
Author: User

1. Data Source introduction:
**************************************** **************************************** ***
In Java, the datasource object is an object that represents the data source entity. A data source is a tool used to store data. It can be a complex large enterprise-level database, or a file with only rows and columns. The data source can be on the server or customer service.

When an application accesses the data source through a connection, a datasource object is used to provide a tool for connecting to the data source. The datasource interface provides two methods for establishing a connection with a data source.
Using the datasource object to establish a connection to a database is more efficient than using the drivermanager interface. Although the use range of the two is very similar, both of them provide methods for establishing a connection to a database, set the maximum connection timeout time to get the stream and log on.

However, the difference between the two is more obvious. Unlike drivermanager, A datasource object can recognize and describe the attributes of the data source it represents, and the work of the datasource object is closely related to JNDI (javatm naming and directory interfaceti, the establishment, release, and Independent Application Management of datasource all rely on the JNDI technology.

In jdbc2.0 or jdbc3.0, all database driver providers must provide a class that implements the datasource interface. To use the data source, you must first register the data source object in JNDI.
If a data source object is registered in JNDI, it has two advantages over drivermanager:
First, the program does not require hard encoding of the loaded database driver information like using drivermanager. programmers can choose to register this data source object in JNDI first, then use a logical name in the program to reference it. JNDI will automatically find the datasource object bound to this name based on your name. Then you can use this datasource object to establish a connection with a specific database.

Second, the second advantage of classes that implement the datasource interface is reflected in the connection pool and distributed transactions. The connection pool significantly improves program efficiency by reusing connections rather than creating a new physical connection. This method is suitable for enterprise-level distributed transactions with busy tasks and heavy workload.
**************************************** **************************************** ***

II. Introduction to JNDI:
**************************************** **************************************** ***
JNDI is an API used to provide directory and naming functions to Java programs. It is designed to be independent from specific directory services, so various directories can be accessed in the same way.

We can simply understand JNDI as a technology that binds objects and names. The object factory is responsible for producing objects, and these objects are bound with unique names. An external program can use its name to obtain a reference to an object.

Directory Service plays a very important role in intranets (enterprise intranet) and internates (Internet, it can access a wide variety of information from numerous users, machines, networks, services, and applications. The Directory Service provides a series of naming Measures to portray the relationships between various entities in a way that humans can understand.

An enterprise computing environment (Computing Environment) is usually composed of several names representing different parts. For example, in an enterprise-level environment, DNS (Domain Name System) is usually regarded as a top-level naming scheme (top-level namein facility) to distinguish different departments or organizations. These departments or organizations can also use directory services such as ladp or NDS.

From the user's point of view, these are compound names composed of different naming schemes. A URL is a typical example. It consists of multiple naming schemes. The directory service application must support this composite composition method.

Java developers who use the directory service API not only benefit from API independence from specific directories or naming services, but also seamless access to (seamless acess) directory objects through multi-layer naming schemes. In fact, any application can bind its own objects to a specific name. This function allows any Java program to search for and obtain any type of objects.

End users can easily use logical names to search for and identify different objects on the network, directory Service developers can use APIs to conveniently switch between different customer services without any changes.
**************************************** **************************************** ***

Iii. Relationship between data source and connection pool:
**************************************** **************************************** ***
Jdbc2.0 provides the javax. SQL. datasource interface, which establishes a connection with the database. When the application accesses the database, you do not need to write the code to connect to the database. You can directly obtain the database connection from the data source.
 
Multiple database connections are established in the datasource. These database connections are stored in the connection pool. When a Java program accesses the database, it only needs to retrieve the idle database connection from the connection pool. When the program accesses the database, it then restores the database connection back to the connection pool.
**************************************** **************************************** ***

4. Relationship between data source and JNDI:
**************************************** **************************************** ***
Datasource objects are provided by Tomcat. Therefore, you cannot create an instance in a program to produce datasource objects. Instead, you need to use another Java technology, JNDI, to obtain references to datasource objects.

Tomcat treats datasource as a configurable JNDI resource. The factory that generates the datasource object is org. Apache. commons. DBCP. basicdatasourcefactory.

The context interface is provided in the javax. Naming package, which binds the object and name, and retrieves the object by name. The main methods in context include:
BIND (string name, object): bind an object to a name.
Lookup (string name): returns the object bound to the specified name.
**************************************** **************************************** ***

V. Data source configuration in Tomcat:
**************************************** **************************************** ***
The configuration of the data source involves modifying the server. XML and Web. XML, in the server. add the element <resource> that defines the data source to XML. add the <resource-ref> element to XML to declare the data referenced by the web application.

A. Add the <resource> element <resource> to server. XML to define the JNDI resource.
  
Attribute description
Name specifies the JNDI name of the resource.
Auth specifies the manager for resource management. It has two optional values: container and application.
Type specifies the Java class name to which the resource belongs

<Resource Name = "JDBC/bookdb"
Auth = "Container"
Type = "javax. SQL. datasource"/>

B. Add the <resourceparams> element to the <resource> element: the <resourceparams> element is used to specify various parameter values.
  
Attribute description
Factory specifies the factory class name of the generated dataresource
Maxactive specifies the maximum number of active connections in the database connection pool. 0 indicates no restriction.
Maxidle specifies the maximum number of idle connections in the database connection pool. 0 indicates no restriction.
Maxwait specifies the maximum time for idle connections in the connection pool. An exception is thrown if the value of-1 is exceeded.
Username specifies the username used to connect to the database
Password indicates the password used to connect to the database.
Driverclassname specifies the JDBC driver used to connect to the database
URL specifies the URL to connect to the database

<Resourceparams name = "JDBC/bookdb">

<Parameter>
<Name> factory </Name>
<Value> org. Apache. commons. DBCP. basicperformancefactory </value>
</Parameter>

<Parameter>
<Name> maxactive </Name>
<Value> 100 </value>
</Parameter>

<Parameter>
<Name> maxidle </Name>
<Value> 30 </value>
</Parameter>

<Parameter>
<Name> maxwait </Name>
<Value> 10000 </value>
</Parameter>

<Parameter>
<Name> username </Name>
<Value> User </value>
</Parameter>

<Parameter>
<Name> password </Name>
<Value> 1234 </value>
</Parameter>

<Parameter>
<Name> driverclassname </Name>
<Value> com. MySQL. JDBC. Driver </value>
</Parameter>

<Parameter>
<Name> URL </Name>
<Value> JDBC: MySQL // localhost: 3306/bookdb? Autoreconnect = true </value>
</Parameter>

</Resourceparams>

C. Add the <resource-ref> element to the Web. xml file: <resource-ref> indicates that the JNDI resource is referenced in the Web application.
  
Attribute description
Description Description of the referenced Resource
Res-ref-name specifies the JNDI name of the referenced resource, which corresponds to the name attribute in the <resource> element.
Res-type specifies the Class Name of the referenced resource, which corresponds to the type attribute in the <resource> element.
Res-auth specifies the manager of the referenced resource, which corresponds to the auth attribute in the <resource> element.

**************************************** **************************************** ***

6. Use data sources in Web applications:
**************************************** **************************************** ***
Javax. Naming. context provides an interface for querying JNDI resources. You can use the data source object in three steps:

A. Get reference to the Data source:
Context CTX = new initalcontext ();
Datasource DS = (datasource) CTX. Lookup ("Java: COMP/ENV/jdbc/bookdb ");

B. Obtain the database connection object:
Connection con = Ds. getconnection ();
  
C. Return to the database to connect to the connection pool:
Con. Close ();

The difference between using the close () method in the connection pool and using the close () method in a non-connection pool is that the former only returns the database connection object to the database connection pool, the connection object is restored to the idle state, instead of closing the database connection, which will directly close the connection to the database.
**************************************** **************************************** ***

7. Publish Web applications using data sources:
**************************************** **************************************** ***
If you access the database directly with JDBC, you can copy the JDBC driver to the WEB-INF/lib directory of the Web application or the common/lib directory under the tomcat installation directory.
  
If you access the database through the data source, because the data source is created and maintained by the servlet container, you must copy the JDBC driver to the common/lib directory under the tomcat installation directory, make sure that the servlet container can access the driver.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.