Start learning with our library of video tutorials taught by experts. Get started

Java Database Integration with JDBC

Using generic getter methods in Java SE 7


From:

Java Database Integration with JDBC

with David Gassner

Video: Using generic getter methods in Java SE 7

So far in this chapter, I have been describing how to retrieve data from ResultSet using specifically-typed Getter methods. For example, in this version of my project, GenericGetters, in my Tours class, I have calls to the methods getInt, getString, and getDouble, and I'm selecting the method to match the data type of the column. So, the tour ID is an integer, so I call getInt, tour name is a string column, so I'll call getString, and so on. In Java 7, there is a new approach, a Generic Getter method called getObject that you can use on every column of ResultSet, and you explicitly data type the return value using a different syntax.
Expand all | Collapse all
  1. 5m 23s
    1. Welcome
      53s
    2. What you should know before starting this course
      1m 20s
    3. Using the exercise files
      3m 10s
  2. 12m 2s
    1. Testing your Java development environment
      5m 14s
    2. Importing a MySQL database
      5m 1s
    3. Creating a database user in MySQL
      1m 47s
  3. 32m 47s
    1. What is JDBC?
      4m 26s
    2. Choosing a JDBC driver
      6m 46s
    3. Connecting to a MySQL database server
      8m 7s
    4. Connecting to a HyperSQL database file
      6m 23s
    5. Executing a static SQL statement
      7m 5s
  4. 17m 42s
    1. Connecting to multiple databases
      6m 24s
    2. Handling JDBC exceptions
      7m 7s
    3. Closing database resources in Java 7
      4m 11s
  5. 47m 25s
    1. Looping through result sets
      8m 23s
    2. Moving the cursor in scrollable result sets
      5m 51s
    3. Limiting the number of fetched rows
      6m 57s
    4. Filtering data with prepared statements
      6m 58s
    5. Calling stored procedures
      5m 48s
    6. Handling multiple values from stored procedures
      5m 54s
    7. Using generic getter methods in Java SE 7
      7m 34s
  6. 45m 23s
    1. Managing data entities with JavaBean classes
      5m 0s
    2. Retrieving a single row as a JavaBean object
      6m 5s
    3. Inserting rows with prepared statements
      8m 2s
    4. Updating rows with prepared statements
      5m 4s
    5. Deleting rows with prepared statements
      4m 9s
    6. Managing data with updatable result sets
      6m 6s
    7. Using a persistent database connection
      6m 43s
    8. Committing and rolling back transactions
      4m 14s
  7. 9m 35s
    1. Getting the DatabaseMetaData object
      3m 40s
    2. Getting column and data type information
      5m 55s
  8. 50s
    1. Next steps
      50s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Java Database Integration with JDBC
2h 51m Intermediate Nov 28, 2012

Viewers: in countries Watching now:

Whether you're building a web- or desktop-based application with Java SE or Java EE, many Java applications need to integrate data from a relational database. This course describes how to read and manage data from relational databases such as MySQL and SQL Server using the Java Database Connectivity (JDBC) API.

Author David Gassner explains how to choose a JDBC driver and connect to one or more databases. He also provides detailed instructions on reading, selecting, and updating data; calling stored procedures; managing data via JavaBean classes or with prepared statements; and working with metadata.

Topics include:
  • Importing a MySQL database
  • Connecting to databases
  • Handling JDBC exceptions
  • Looping through result sets
  • Limiting the number of fetched rows
  • Filtering data with prepared statements
  • Calling stored procedures
  • Inserting, updating, and deleting rows with prepared statements
  • Using a persistent database connection
  • Committing and rolling back transactions
Subjects:
Developer Databases Programming Languages
Software:
Java
Author:
David Gassner

Using generic getter methods in Java SE 7

So far in this chapter, I have been describing how to retrieve data from ResultSet using specifically-typed Getter methods. For example, in this version of my project, GenericGetters, in my Tours class, I have calls to the methods getInt, getString, and getDouble, and I'm selecting the method to match the data type of the column. So, the tour ID is an integer, so I call getInt, tour name is a string column, so I'll call getString, and so on. In Java 7, there is a new approach, a Generic Getter method called getObject that you can use on every column of ResultSet, and you explicitly data type the return value using a different syntax.

Now again, this new Generic Getter method is only available in Java 7. So if you're using an older version of Java, you should stick with these explicitly data typed method calls. But if you are working with Java 7 and therefore JDBC 4.1, this new approach is just another option, another tool in your toolkit. I'll start this exercise by re-factoring this code a bit. I'm going to take the expression that's retrieving the tourId, and I'll extract it to a local variable of the method. I'll select the expression, then I'll right-click, scroll down and choose Refactor, and then Extract Local Variable.

I'll name my new variable the same as the column name, tourId. So that creates a local variable here, and then I'm using that value on the next line to build my string buffer. I'll do the same sort of re-factoring for the tourName. This is all just to make the code a little bit more readable. I'll select the expression, right-click, choose Refactor > Extract Local Variable, and again, I'll name the new variable to match the column name, tour name. I'll group these two variable declarations together, and then I'll take another that already exists, the declaration of the price variable, and I'll move that up.

So now I have one section of code where I'm getting all the values I need from the current row. I'm going to reformat the code a little bit, and make it even easier to read, and now I'm ready to use the new Generic Getter method. I'm going to keep a copy of this code around so I can compare the two styles of coding to each other. I'll select and copy and then paste in, and then I'll comment out the second version, and I'll make the changes to the first version. Here's how you use the Generic Getter. I'll start with the integer. Instead of calling getInt and passing in either the name of the column or the ordinal position of the column as an integer, you call getObject.

So, I'll get rid of that, and instead of getInt, I'll call getObject. You'll see that there are a few versions of this method, but I'm using this version, the one that accepts a column label as the first argument and then a class. The class will determine the data type that will be returned from the method. You'll see that we're using the diamond operator, and the T in the middle means type. What is the data type that we're looking for? So I'll call getObject, and just as before, I'll pass in the name of the column that I'm retrieving from, and then, I'll pass in a class and its class field, and it looks like this for an integer, Integer.class.

That means that I want to retrieve the tourId column, and I want to data type it as a class. Now, you might think that I would have to explicitly cast the value as I'm passing it back. For example, adding casting syntax at the beginning. But because of the way the getObject method is written, when I say that I'm passing in an integer class here, that's the class that's going to be returned, and so it will automatically be returned as my primitive integer, and I don't need this casting syntax. Now, let's do the same thing with the string.

I'll get rid of the call to the getString method, and instead I'll call getObject, once again, I'll call the version that accepts the name of the column and the type. I'll pass in the name of the column as tour name, and the type will be string.class. Finally, I'll do the same thing with the price. I'm retrieving a double value. So I'll call the getObject method, and I'll pass in the name of the column, price, and the data type which I'm going to set initially as Double.class. So, take a look at these two versions of the code. In the first one, you're calling the same method over and over again, getObject, and you're setting the data type using that second argument.

In the second version, which is the older version, you're setting the data type with the actual method names. I'll run this application, and I'll see that it works exactly the same as it has in previous versions of the project. If you see a pop-up dialog asking you whether you want to run an application or an applet, choose Java application. But here's a little problem with this version of the code. I'll go back to my Main class and show that I have started off working against MySQL, and this code works with MySQL. But now I'm going to switch to HSQLDB or HyperSQL, and I'll run the code again.

And this time I get an error. Depending on the state of your installation of Eclipse, you might not see this dialog. Instead, you might go right to the debug perspective. I'll see that I'm getting a ClassCastException which was not caught by MySQL Exception catch clause. I need to add a little bit more try catch code to see what's happening. So, I'll terminate the project and go back to my code, and I'm going to add in another catch section. And this time, instead of SQLException, I'll catch the global exception object, Exception.

And here, I'll just do a little bit of system error output, and I'll pass in the Error object. I'll run the code again, and this time I can see the explicit error, BigDecimal cannot be cast to double. So what's going on here? When you call the getObject method with a double column or a float, the specification for JDBC says that a BigDecimal will be returned, not a double or a float. Now, if you have watched my Java Essential Training course, you might remember that I described why the Big Decimal class exists.

The double and float objects can't be guaranteed to be absolutely precise because of the nature of how floating-point arithmetic happens on the computer, you'll frequently have additional decimal values that you don't want. Whereas the BigDecimal object can always return a very specific value. With some database drivers, the BigDecimal can be converted to the Double, and that was the case with MySQL. But with other database drivers, such as HyperSQLs, you have to always use the BigDecimal. So, for portability between databases, if you're working with columns that are doubles, floats, currency, or anything else that might have fractional values, I recommend always returning a BigDecimal.

So I'm going to change the data type of the value that I'm returning into, the price, and I'll change it to BigDecimal. I'll make sure to choose it so that I get an import statement for the class. Then I'll go to my getObject call, and I'll change that from Double.class to BigDecimal.class. I'll save and run the code again. And with HyperSQL, it now works, where it broke before. I'll go back to my Main class and change back to MySQL, and I'll run the code again. And I'll see that it works there as well.

If you use the BigDecimal to contain your doubles and floats, you'll pretty much guarantee that things work fine across different databases. But if you try to stuff things into a double or a float value using this new Generic Getter method, it will work on some databases but not on others. So that's a look at how you can use the new Generic Getter method. In the rest of the code throughout this course, I'm going to continue to use the older style because it is compatible with older versions of Java. But if you're working with Java 7, you might want to upgrade to this new version of the code.

There are currently no FAQs about Java Database Integration with JDBC.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Database Integration with JDBC.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked