Welcome!

Blog Feed Post

Configuring a MySQL JDBC Connection Pool and JDBC Resource for GlassFish using NetBeans

This tutorial assumes that you have installed the Java EE version of NetBeans 8.02. If you are using Windows then it is further assumed that you have replaced the default GlassFish server instance in NetBeans with a new instance with its own folder for the domain. See my previous article “Creating a New Instance of GlassFish in NetBeans IDE” On an Apple Mac and likely on Linux it is not necessary to do this.

The other day I presented to my students the steps necessary to make GlassFish responsible for JDBC connections. As I went through the steps I realized that I needed to record the steps for my students to reference. Here then are these steps.

Step 1: Add the MySQL driver to the GlassFish Domain

Before we even start NetBeans we must do a bit of preliminary work. GlassFish does not include the MySQL driver or any other driver in its distribution. One exception is that it does include a complete implementation of the Derby database and Derby is the default data source for GlassFish.

Go to the MySql Connector/J download site at http://dev.mysql.com/downloads/connector/j/ and download the latest version. I recommend downloading the Platform Independent version. If your OS is Windows download the ZIP archive otherwise download the TAR archive. You are looking for the driver file named mysql-connector-java-5.1.34-bin.jar in the archive.

The driver file must now be copied to the lib folder in the directory where you placed your domain. On my system the folder is located at C:\Users\Ken\personal_domain\lib. If GlassFish is already running then you will have to restart it so that it picks up the new library.

Step 2: Create a Database Connection in NetBeans

One feature I have always liked in NetBeans is that it has an interface for working with databases. All that is required is that you create a connection to the database. It also has additional features for managing a MySQL server but we won’t need those. If you have not already started your MySQL DBMS then do that now. I also assume that the database you wish to connect to already exists.

Go to the Services tab and right mouse click on New Connection.

Image0120

In the next dialog you must choose the database driver you wish to use. It defaults to Java DB (Embedded). Pull down the combo box labeled Driver: and select MySQL (Connector/J driver).

Image0220

Click on Next and you will now see the Customize Connection dialog. Here you can enter the details of the connection. On my system the server is localhost and the database name is Aquarium. Here is what my dialog looks like.

Image0320

Notice the Test Connection button. I have clicked on mine and so I have the message Connection Succeeded. Click on Next.

Image0420

There is nothing to do on this dialog so click on Next.

Image0520

On this last dialog you have the option of assigning a name to the connection. By default it uses the URL but I prefer a more meaningful name. I have used AquariumMySQL.

Image0620

Click on Finish and the connection will appear under Databases.

Image0720

If the icon next to AquariumMySQL has what looks like a crack in it similar to the jdbc:derby connection then this means that a connection to the database could not be made. Verify that the database is running and is accessible. If it is then delete the connection and start over.

Step 3: Create a Web Application Project in NetBeans

If you have not already done so create a New Project in NetBeans. My preference is to create a New Project in the Maven category of a Web Application project. You could also create a New Project of the Java Web category of a Web Application project.

Image0820

Click on Next. In this next dialog you can give the project a name and a location in your file system. The Artifact Id, Group Id and Version are used by Maven.

Image11a20

The final dialog lets you select the application server that your application will use and the version of Java EE that your code must be compliant with.

Image11b20

Here is my project ready for the next step.

Image0920

Step 4: Create the GlassFish JDBC Resource

For GlassFish to manage your database connection you need to set up two resources, a JDBC Connection Pool and a JDBC Resource. You can create both in one step by creating a GlassFish JDBC Resource because you can create the Connection Pool as part of the operation.

Right mouse click on the project name and select New and then Other …

Image1020

Scroll down the Categories list and select GlassFish. In the File Types list select JDBC Resource.

Image1120

Click on Next. The next dialog is the General Attributes. Click on the radio button for Create New JDBC Connection Pool. In the text field JNDI Name enter a name that is unique for the project. JNDI names for connection resources always begin with jdbc/ followed by a name that starts with a lower case letter. I have used jdbc/myAquarium.

Image1220

Click on Next. There is nothing for us to enter on the Properties dialog.

Image1320

Click on Next. On the Choose Database Connection dialog we will give our connection pool a name and select the database connection we created in Step 2. Notice that in the list of available connections you are shown the connection URL and not the name you assigned to it.

Image1420

Click on Next. On the Add Connection Pool Properties dialog you will see the connection URL and the user name and password. We do need to make one change. The resource type shows javax.sql.DataSource and we must change it to javax.sql.ConnectionPoolDataSource.

Image1520

Click on Next. There is nothing we need to change on Add Connection Pool Optional Properties so click on Finish.

A new folder has appeared in the Projects view named Other Sources. It contains a sub folder named setup. In this folder is the file glassfish-resources.xml.

Image1620

The glassfish-resources.xml file will contain the following. I have reformatted the file for easier viewing.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-resource enabled="true" jndi-name="jdbc/myAquarium" object-type="user" pool-name="aquariumPool">
        <description/>
    </jdbc-resource>
    <jdbc-connection-pool allow-non-component-callers="false" 
                        associate-with-thread="false" 
                        connection-creation-retry-attempts="0" 
                        connection-creation-retry-interval-in-seconds="10" 
                        connection-leak-reclaim="false" 
                        connection-leak-timeout-in-seconds="0" 
                        connection-validation-method="auto-commit" 
                        datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" 
                        fail-all-connections="false" idle-timeout-in-seconds="300" 
                        is-connection-validation-required="false" is-isolation-level-guaranteed="true" 
                        lazy-connection-association="false" 
                        lazy-connection-enlistment="false" 
                        match-connections="false" 
                        max-connection-usage-count="0" 
                        max-pool-size="32" 
                        max-wait-time-in-millis="60000" 
                        name="aquariumPool" 
                        non-transactional-connections="false" 
                        pool-resize-quantity="2" 
                        res-type="javax.sql.ConnectionPoolDataSource" 
                        statement-timeout-in-seconds="-1" 
                        steady-pool-size="8" 
                        validate-atmost-once-period-in-seconds="0" 
                        wrap-jdbc-objects="false">
        <property name="URL" value="jdbc:mysql://localhost:3306/Aquarium?zeroDateTimeBehavior=convertToNull"/>
        <property name="User" value="fish"/>
        <property name="Password" value="fish"/>
    </jdbc-connection-pool>
</resources>
glassfish-resources.xml

Step 4: Configure GlassFish with glassfish-resources.xml

The glassfish-resources.xml file when included in the application’s WAR file should configure the resource and pool for the application. We can also use this file to configure GlassFish directly and therefore verify that it is the correct configuration.

Go to the Services tab and select Servers and then right mouse click on GlassFish. If GlassFish is not running then click on Start. You can tell if GlassFish is running based on whether Start is black (not started) or grey (started).

With the server started click on View Domain Admin Console.

Image1720

Your web browser will now open and show you the GlassFish console. If you assigned a user name and password to the server you will have to enter this information before you see the console.

Image1820

In the Common Tasks tree select Resources. You should now see in the panel adjacent to the tree the following.

Image1920

Click on Add Resources. You should now see:

Image2020

In the Location click on Choose File and locate your glassfish-resources.xml file. Mine is found at D:\NetBeansProjects\GlassFishTutorial\src\main\setup. You should now see:

Image2120

Click on OK. If everything has gone well you should see:

Image2220

The final task in this step is to test if the connection works. In the Common Tasks tree select Resources, JDBC, JDBC Connection Pools and aquariumPool.

Image2320

Click on Ping. You should see:

Image2520

If the Ping was not successful review the steps.

The resources are now visible in NetBeans.

Image2620

You are ready to code!

Read the original blog entry...

More Stories By Ken Fogel

In 1980 I bought for myself the most wonderful toy of the day, the Apple ][+. Obsession followed quickly and by 1983 I was writing software for small and medium sized businesses in Montreal for both the Apple and the IBM PC under the company name Omnibus Systems. In the evenings I taught continuing education courses that demystified the computer to the first generation of workers who found themselves with their typewriter on the scrap heap and a PC with WordStar taking its place.

In 1990 I was invited to join the faculty at Dawson College in the Computer Science Technology program. When I joined the program the primary language was COBOL and my responsibility was to teach small systems languages such as BASIC and C/C++.

Today I am now the chairperson and program coordinator of the Computer Science Technology program at Dawson. The program's primary language is Java and the focus is on enterprise programming.

I like to write about the every day problems my students and I face in using various languages and platforms to get the job done. And from time to time I stray from the path and write about what I plan to do, what I actually get around to doing, and what I imagine I am doing.

@omniprof

Latest Stories
Microsoft Azure Container Services can be used for container deployment in a variety of ways including support for Orchestrators like Kubernetes, Docker Swarm and Mesos. However, the abstraction for app development that support application self-healing, scaling and so on may not be at the right level. Helm and Draft makes this a lot easier. In this primarily demo-driven session at @DevOpsSummit at 21st Cloud Expo, Raghavan "Rags" Srinivas, a Cloud Solutions Architect/Evangelist at Microsoft, wi...
Containers are rapidly finding their way into enterprise data centers, but change is difficult. How do enterprises transform their architecture with technologies like containers without losing the reliable components of their current solutions? In his session at @DevOpsSummit at 21st Cloud Expo, Tony Campbell, Director, Educational Services at CoreOS, will explore the challenges organizations are facing today as they move to containers and go over how Kubernetes applications can deploy with lega...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. ANSeeN are the measurement electronics maker for X-ray and Gamma-ray and Neutron measurement equipment such as spectrometers, pulse shape analyzer, and CdTe-FPD. For more information, visit http://anseen.com/.
Today most companies are adopting or evaluating container technology - Docker in particular - to speed up application deployment, drive down cost, ease management and make application delivery more flexible overall. As with most new architectures, this dream takes significant work to become a reality. Even when you do get your application componentized enough and packaged properly, there are still challenges for DevOps teams to making the shift to continuous delivery and achieving that reducti...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterprise adopting a hybrid or public cloud needs systems and tools that provide: Agility: ability to deliver applications and services faster, even in complex hybrid environments Easier manageability: enable reliable connectivity with complete oversight as the data center network evolves Greater efficiency: eliminate wasted effort while reducing errors and optimize asset utilization Security: imple...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
DevOps at Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to w...
When it comes to cloud computing, the ability to turn massive amounts of compute cores on and off on demand sounds attractive to IT staff, who need to manage peaks and valleys in user activity. With cloud bursting, the majority of the data can stay on premises while tapping into compute from public cloud providers, reducing risk and minimizing need to move large files. In his session at 18th Cloud Expo, Scott Jeschonek, Director of Product Management at Avere Systems, discussed the IT and busine...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...