When configure DataSource on JEE container Glassfish, There are 2 things need to be set, JDBC Resource and JDBC Connection Pools.
What's the difference and why are these two items? What's the relation between them? We can answer that by inspecting the Java JDBC API, mainly in package javax.sql
1. How to connect to DB
To work with DB in Java, the application must have a connections (java.sql.Connection) to the database. There are 2 ways to get a connection in JDBC:
- Method 1, using static method, DriverManager.getConnection(url). This is a very old way, still valid, only used in small standalone applications, doesn't support pooling.
- Method2, using DataSource interface. Recommended. In most case work with JNDI lookup to get one from a container.
2. The hierarchy of DataSource
There are some points need to be noticed about this diagram:
They are all interfaces. No concrete class at all.
There are 3 interfaces related to data source, DataSource/ConnectionPoolDataSource/XADataSource.
Application Java code will ONLY come into contact with the green part. DataSource and Connection.
ConnectionPoolDataSource instance can create PooledConnection instance(pooled...you know,name tells all), XADataSrouce can create XAConnection (for distributed transaction)
The ConnectionPoolDataSource, although may sounds like, but is not a Child of DataSource. In other words, A ConnectionPoolDataSource instance can't be simply casted to DataSource instance. So inside a DataSource instance, the real work will somehow be delegate to a ConnectionPoolDataSource/XADataSouce.
Same thing applied to Connection. The Connection has nothing to do with PooledConnection, although they looks similar. No casting but delegation.
Up to know you should understand the relationship between JDBC Resource and JDBC Connection Pools in Glassfish Administration GUI. Think JDBC Resource as DataSource and JDBC Connection Pools as ConnectionPoolDataSource.
3. Using MySQL in Glassfish
Let's use MySQL's official developer guide on "Using Connector/J with GlashFish" as a testify. On this document, the configuration has 2 steps:
- step1. Creating a Connection Pool, filling in information like DB's IP address, username and password for make "real" connections to database.
- step2. Create a JDBC Resource. choose a pool created in step 1 and set a JNDI name for it. We can say the JDBC Resource HAS-A pool.
The steps can pretty much demonstrate the hierarchy of DataSource in JDBC API, which once get understood will make the configuration steps make sense and easy to remember.
0 comments:
Post a Comment