title: Tutorial_2_Background
—
In this tutorial, you experiment with queries to get a feel for how the interface actually behaves. For this tutorial we stick to using JUnit 4 to write a “test” for each of our tutorials.
Background
The Entity Manager allows you to create queries using its own query language called Java Persistence Query Language, JPQL. Rather than cover the syntax directly, this tutorial presents you with several queries and asks you to use each one of these queries against the entities we created in JPA_Tutorial_1_Getting_Started.
Queries in JPQL are not like SQL queries. Where a SQL query deals with tables and columns, a JPQL query deals with objects and attributes. In many cases there is no difference, but it is possible that a single object maps to multiple tables (think of a many to many relationship with join tables). When you are working with JPQL, you don’t think about join tables; you think in terms of objects and their relationships. As you’ll find out, the name of your Objects and attributes are case sensitive.
For this tutorial, we continue using JUnit 4 by writing a unit test for each of of a series of provided queries. Each unit test will perform some set up, execute a query and then it will programmatically validate the results. In many cases we won’t know the results, so we’ll actually run the unit test, figure out the results then effectively document how the query interface works by putting asserts in our unit tests.
Term
Description
JUnit
A Unit Test tool. JUnit allows you to create individual test methods. Each test method runs alone and performs any necessary setup, executes code under test, validates that the results programmatically (so you don’t have to look at a bunch of output) and then cleans up after itself).
Unit Test
A single test method that tests one thing. For this tutorial, we will use one unit test method per query. To denote a method as a test method, we use the @Test annotation.
Query
An expression executed against the database to create, retrieve, updated= and remove records from tables.
JPQL
A query language where you express what you want in terms of Objects and relationships between objects instead of directly in SQL using tables and columns.
The following queries will get you started experimenting with the JPA query interface. Your task is to do the following for each query:
Review the query
Predict the results before you do anything
Compose a unit test to exercise the query (make sure your test produces no output)
Execute the test to see if your prediction was correct
Make the test pass
The Queries
title: Tutorial_2_The_Queries
—
Queries
In these example, the variable “em” is an entity manger initialized just like it was in the first tutorial.
Empty String
Setup: None required
Unknown Class
Setup: None required
Minimal “Get All”
Setup: None required
Successfully Get a Single Object
Setup: Insert exactly 1 Person entity in the database
Unsuccessfully Try to get a Single Object When There Are None
Setup: Make sure there are no Person entities in the database
Unsuccessfully Try to get a Single Object With Too Many
Setup: Insert two or more Person entities in the database
Find By Primary Key
Setup: Insert a Person in the database, make sure to get the key of the object inserted
Unsuccessfully Find by Primary Key
Setup: None required
Search Using Query Parameter and Storing Result as List<?>
Setup: Insert one person record where the Person’s first name = “Brett”.
Search Using Query Parameter and Storing Result as List
Setup: Insert one person record where the Person’s first name = “Brett”.
Do Find by Primary Key and Queries Return == Objects
Setup: Insert one person record and store the primary key. Also make sure the first name of the person equals “Brett”.
Use Wrong Class Name
Setup: None required
Use Wrong Field Name
Setup: None required
Use Column Name Instead of Field Name
Setup: None required, but maybe insert a single person whose first name = “Brett”.
Use a Parameter but Provide Wrong Index
Setup: None required
Set Parameter Where There are None: Version 1
Setup: None required
Set Parameter When There Are None: Version 2
Setup: None required
JPA Tutorial 2 Project Setup
For this next section, where you see ****, replace it with **JpaTutorial2**.
title: JPA_Tutorial_Project_Setup
—
Create Java Project
Next we need to create a Java project. We’ll keep the source separate from the bin directory:
Pull down the File menu and select New:Project
Select Java Project and click on Next
Enter a project name: ****, again read [this](JPA_Tutorial_1_Getting_Started#SideBarJpaClassPath) to know why I did not use a space in the project name.
Make sure “Create new project in workspace” is selected.
Make sure the JRE selected is 1.5.x or higher. If such a JRE does not show in the list, you can add it through Window->Preferences->JAVA->Installed JRE’s.
Select Create separate source and output folders
Click Finish
Create folders and packages
Expand your **** folder
Select the src directory
Right-click, select new:Folder
Use the name META-INF
Make sure **** is still selected, right-click and select **New:Source Folder**
Enter test and click OK
Add Required Libraries
We now need to add two libraries. Note that these steps assume you’ve already worked through the first tutorial and are working in the same workspace. If you, you’ll need to create user libraries. Review Creating User Libraries.
Edit the project properties. Select your **** and either press **alt-enter** or right-click and select properties.
Select Java Build Path
Click on the Libraries tab
Click on Add Library
Select User Libraries and click Next
Select JPA_JSE by click on the check box
Click OK
Click on Add Library again
Click on JUnit
Click Next
In the pull-down list, select JUnit 4
Click Finish
Click OK
If you’d like some background information on JUnit, please go here.
Configure Persistence Unit
title: JpaPersistenceUnit
—
We now need to create the Persistent Unit definition. We are going to create a file called persistence.xml in the src/META-INF directory with the following contents:
persistence.xml
The Steps
Expand your ****
Select the src directory
Find the src/META-INF directory (if one does not exist, right-click, select New:Folder, enter META-INF and press enter)
Right click the src/META-INF, select new:File.
Enter persistence.xml for the name and press “OK” (Note: all lowercase. It won’t make a difference on Windows XP but it will on Unix.)
Copy the contents (above) into the file and save it
Copy Entities From JpaTutorial1
Open up your Tutorial1 project
Expand the src folder
Select entity
Right-click, select Copy
Open up your Tutorial2 project
Select the src folder
Right-click, select Paste
A First Test/Example
title: Tutorial_2_The_First_Example
—
Test Setup
We have a bit of setup/initialization code we need to do before we can get started. We have seen all of this code before in Tutorial 1. The difference here is that we are going to work though some refactorings to get to where we were in tutorial 1. Here are the various parts:
Configure the Logger
Create the Entity Manager Factory
Create the Entity Manager
Create Entities
Use the Entity Manager
Perform a Query and Verify it Works
The Whole Thing
Here’s all of this put together. Note that we’re going to refactor this heavily coming up.
Get it Running
After creating your Test Class, verify that it runs and that this test passes:
Right-click anywhere in your class’ editor pane.
Select Run As:JUnit Test
Second Example and Refactoring
title: Tutorial_2_Second_Example
—
There are several things for which we need some support code:
Per test method setup
Per test method cleanup
One-time logger initialization
Inserting a single record
Before putting all of this together, let’s examine each of these things.
Per test method setup
This creates two fields. We then use the JUnit 4 @Before annotation to initialize that before the execution of each individual unit test. For details, please see here.
Per test method cleanup
This example uses the JUnit 4 @After annotation to cleanup up resources we’ve allocation after the execution of each individual unit test. For details, please see here.
One-time logger initialization
This example uses the JUnit 4 @BeforeClass annotation to perform one-time initialization for the whole class. For details, please see here.
In this case, the first line in the method performs basic configuration of the Log4J logging system. The second line sets the default logging level for any class whose package starts with org to ERROR. This significantly reduces the output. It is possible to reduce the output one level further by setting it to FATAL.
Inserting a single record
Rewrite and New Method
With these changes in hand, we can rewrite the previous test method as follows:
Here’s a second test to justify all of this refactoring.
Putting it all Together
And finally, here’s all of the above changes together in one place.
Comments