16.10.2015 Views

Getting Startedwith pureQuery

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10 – Inline Programming Style 187<br />

application. Most of the “In practice” sections ask you to add a line or two of <strong>pureQuery</strong><br />

code to either the class or the interface. Look for the comments that say TODO: Add<br />

<strong>pureQuery</strong> code here. to know where to add the code.<br />

10.2.2 In practice: Create a Data object in the displayLogin() method<br />

The Human Resources Manager application creates a single instance of Data in the<br />

displayLogin() method and passes that instance to other methods, as required.<br />

Finally, before the application exits, it closes the instance of Data. Modify the<br />

displayLogin() method so that it creates and closes an instance of Data.<br />

10.2.2.1 Add code to the displayLogin() method to create the Data object<br />

Since we are using the inline programming style, we need a getData method that does<br />

not take a Class interfaceClass parameter. We will be using a database, and we<br />

want <strong>pureQuery</strong> to create a connection by using the DataSource object that is in<br />

hrm.HRMDataSourceFactory, so we need a method that has a<br />

javax.sql.DataSource parameter. We choose the method shown in Listing 10.2.<br />

DataFactory.getData (DataSource ds)<br />

Listing 10.2 - The getData method that we will use to create an instance of Data<br />

The displayLogin() method contains a declaration for a variable named data. Add<br />

code that creates an instance of Data and assigns the result to data. Look for a comment<br />

that says TODO: Add <strong>pureQuery</strong> code here. to know where you need to add the new<br />

code. Listing 10.3 shows the updated version of the code.<br />

// Get the DataSource, and use it to create an instance of Data.<br />

DataSource dataSource = HRMDataSourceFactory.getDataSourceForApplication<br />

();<br />

data = DataFactory.getData (dataSource);<br />

Listing 10.3 - Add code to the displayLogin() method that creates an instance of<br />

Data<br />

10.2.2.2 Close the Data object when your application no longer needs it<br />

Modify the finally block in displayLogin() to close the instance of Data. This<br />

closes the java.sql.Connection object that <strong>pureQuery</strong> created for the instance of<br />

Data. Listing 10.4 shows the code that you need to add.<br />

// Close the instance of Data. This closes the<br />

// database connection that it contains.<br />

if (null != data) {<br />

data.close ();<br />

}<br />

Listing 10.4 - Add code to the displayLogin() method that closes the instance of<br />

Data

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!