Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Retrieving a single row as a JavaBean object

From: Java Database Integration with JDBC

Video: Retrieving a single row as a JavaBean object

In a previous video I described how to create a JavaBean class to represent the structure of the database table. The Admin class has one private field for each column of the Admin table and the datatypes of the class matched the datatypes of the columns. There are private fields and public getters and setters. The names match the JavaBean convention where the getters start with the word get and the setters with the words set and then the rest of the names of the methods match the fields. The fields can match the database column names, and they do here, but they don't have to.

Retrieving a single row as a JavaBean object

In a previous video I described how to create a JavaBean class to represent the structure of the database table. The Admin class has one private field for each column of the Admin table and the datatypes of the class matched the datatypes of the columns. There are private fields and public getters and setters. The names match the JavaBean convention where the getters start with the word get and the setters with the words set and then the rest of the names of the methods match the fields. The fields can match the database column names, and they do here, but they don't have to.

Now I'm going to show how to use this JavaBean class to represent a single row of data retrieved from a table. I am working in a version of my project called RetrieveBean, and in this version of the project my AdminManager class has a new method called getRow. The getRow method receives a single argument datatype as an integer. I have named it to match the database column name Admin ID, and that's the primary key column of the database table. Then there is an SQL variable, a string that has the statement I'm going to execute with a question mark for the placeholder. That value will be provided by the end user.

Then I'm creating a result set, a connection, and a prepared statement. I'm taking the value passed in, in the argument and setting it for the placeholder and then executing the query. But for the moment I'm just returning null. Now, I'm going to replace the return statement with the logic that takes the data received from the query and wraps it in an instance of my JavaBean. I will move the cursor after the call to execute query, and I'll add logic to test whether I got back data. If the query returns one row of data, I will be able to move the cursor from its initial position before the first row to the first row by calling the result sets next method.

So I will use an if statement, if rs.next. If this returns true, it means I got data back. But if it returns false, that means that the user provided a value that doesn't match anything in the database table. I'll move my return statement to within the else clause, and I'll also output an error, No rows were found, now I will add logic to wrap up the data that was found inside the if statement. So if the next method returns true, then I have data to work with. I will create an instance of my Admin class.

Remember that it's in the beans package, and you do need an import for it. I will name this new object bean, and I will instantiate it with the classes No arguments constructor method. Now I will set its fields using its setter methods. First, I will set the primary key bean.setAdminId, and I will just use the value that was passed in as the argument. Next, I will set the two string fields, username and password, and I'll use the values from the result set. I will call bean.set username, and I will pass in rs.getString, and I will identify the column I want by its name, userName. Then I'll set the password field.

Once again, I'm using the setString method. For a database table that has more columns, simply call as many versions of the set method as you need to and use the appropriate methods of the result set to get the datatypes that you need. Get string for strings, get double and get int for integers and doubles, and so on. Now my bean object is complete. I have instantiated it, and I have set its values, and I will return it to the calling context. And that's the complete method. I will review all of the code.

The primary key value is passed in as an argument, the SQL statement has a placeholder for that primary key value, I am using a prepared statement object so I can pass the value in using one of the setter methods, and I am executing the query. If I get data back, I wrap that data in an instance of my JavaBean class and return it, if I don't get data back, I return null. Now, let's go to the main class and call this method. I will place the cursor after the call to the AdminManger's displayAllRows method, and I will add code that lets the user indicate what row they want to work with.

I will declare a new variable called AdminId, and I will get its value from a new method of the InputHelper class called getInteger input. I will set a prompt of Select a row. Now I will use that value to get a JavaBean object representing the matching data. I will declare a new JavaBean object, and I will use the Admin data type, and I will set the name of the object as bean, and I will instantiate it using AdminManager.getRow, and I will pass in the AdminId. Now I will test whether I got data back from the query.

I will use an if else clause. I will set my condition to if, bean has a value of null. So if the bean is null, that means I didn't get any data back. In my output manager's method, I am already outputting an error message. I am going to move that to the main class. I will cut it from here and paste it into my main class in my if clause. But then in the else clause, if I did get data back, I will display that data's information. I will use a series of system outputs.

The first one will have a label of AdminId and a call to the getAdminId method of the JavaBean object. I will duplicate that line of code a couple of times and then I will change the labels and the methods that I'm calling. For the second one, I will use UserName as the label, and I will call getUserName. And for the third one, I will set the label to Password, and I'll call getPassword. So now I am ready to test my application. I'll make sure that I saved all my classes, then I will go back to my main class and run the application, I'll type in a value of 2, which won't match row, and I'll get back the error message, No rows were found.

But then I'll run the code again, and I'll pass in the correct value of one, and I get back the data. So now I have an object that I can pass around the application. I can get the data object from one method and pass it into another and in the next set of videos I'll show you how to use this object to manage updates and deletes of existing data.

Show transcript

This video is part of

Image for Java Database Integration with JDBC
Java Database Integration with JDBC

32 video lessons · 6355 viewers

David Gassner
Author

 
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

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

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.


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.

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
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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.