1 Java Persistence API (JPA) )
1 Java Persistence API (JPA) )
In this chapter, we introduce the student to the concept of JPA, that is Java Persistence
API. We also demonstrate the implementation of JPA in a web development
environment.
JPA is an acronym for Java Persistence API. So this is an API that is used to persist
objects in a Relational Database. The API allows programmers to interact with a
Relational Database in an Object-Oriented manner. Through the API, objects
(instances of classes) are mapped to tables, and their fields to columns of tables. The
state of an object is stored as a row in tables.
Previously, when writing databased applications, we used the JDBC (Java Database
Connectivity) API. The API required us to use SQL statements in order to interact with
the database. The figure below shows the architecture we implemented.
1
A persistence provider is a piece of code that works similar to a compiler. The provider
implements JPA. Part of the task involves conversion of objects into SQL statements
for interaction with the database. The provider also performs the reverse conversion
where database results needs to be sent back to an application. In this case the
provider will convert SQL statements into an object. There are many persistence
providers out there, but the one we use is called Hibernate.
1.2 Annotations
The classes and annotations used in JPA are located in a package called
javax.persistence. Annotations are special instructions meant for execution by the
container. They tell a container what to do with the resource that includes a particular
annotation. Let us look at some of the annotations contained in the package.
1.2.1 @Entity
Example
Let us create a Person entity that can be mapped to a Person table in the database.
2
The Person class is an entity because of the @Entity annotation. The entity is
mapped to the Person table in the database. This is the default state. A table takes
the name of an entity.
1.2.2 @Table
The @Table annotation is used to customise a mapped table. The annotation allows
a programmer to map an entity to a different table in the database. The annotation has
an attribute called name that makes this customisation possible.
Example
Let us map the Person entity to the Person_TBL table in the database.
The name attribute of the @Table annotation allows us to give the name of the table
we want to map our entity to in the database.
3
1.2.3 @Id
The @Id annotation is used to denote one of the instance fields of an entity as a
primary key. The primary key is used to uniquely identify a record in a table.
Example
Let us create a Person entity with a primary key called id.
The PERSON_TBL table has a column called id, corresponding to the id field of the
Person entity. The column will store the primary keys of the respective records.
1.2.4 @GeneratedValue
Example
Let us create a Person entity whose primary key should be automatically generated
by the persistence provider.
4
The primary keys in PERSON_TBL will be automatically generated. The programmer
will not provide the values.
1.2.5 @Column
The @Column annotation is used to customise the columns of tables. The @Column
annotation allows us to map a field name to a different column name. It also allows to
state whether columns should accept null values or not, and also the size of columns.
Example
Let us create a Person entity that maps to a PERSON_TBL table in the database.
The entity must have three fields, a primary key field called id; firstName; and
lastName. The firstName field must be mapped to the name column in the table. The
field must not be nullable and its maximum length must be 20.
As can be seen, the id and lastName fields are mapped to the same column names
in the table. But the firstName field is mapped to the customised name column.
5
1.2.6 @Transient
The @Transient annotation denotes that an entity’s field must not be persisted in the
database.
Example
Let us create a Person entity that maps to a PERSON_TBL table in the database.
The entity must have three fields, a primary key field called id; firstName; and
lastName. The firstName field must be mapped to the name column in the table. The
field must not be nullable and its maximum length must be 20. The lastName must not
be persisted in the database.
As can be seen, there’s no column for the lastName field since it is transient.
1.2.7 @Temporal
The @Temporal annotation is used to used to persist date, time and timestamp.
Example
Let us create a Person entity that maps to a PERSON_TBL table in the database.
The entity must have four fields, a primary key field called id; firstName; lastName;
and creation date. The firstName field must be mapped to the name column in the
table. The field must not be nullable and its maximum length must be 20. The
6
lastName must not be persisted into the database. The creation date must be the
timestamp.
1.2.8 @SecondaryTable
The @SecondaryTable annotation is used when we want to map some of the entity’s
fields to another table.
Example
Let us create a Person entity that maps to a PERSON_TBL table in the database. The
entity must have five fields, a primary key field called id; firstName; lastName;
creation date; street; and city. The firstName field must be mapped to the name
column in the table. The field must not be nullable and its maximum length must be
20. The lastName must not be persisted into the database. The creation date should
be the timestamp. The street and city fields must be persisted to a table called
ADDRESS_TBL.
7
1.2.9 @SecondaryTables
The @SecondaryTables annotation is used for mapping some of the entity’s fields to
other tables.
Example
Let us create a Person entity that maps to a PERSON_TBL table in the database. The
entity must have seven fields, a primary key field called id; firstName; lastName;
creation date; street; city; and code. The firstName field must be mapped to the
name column in the table. The field must not be nullable and its maximum length must
be 20. The lastName must not be persisted into the database. The creation date
should be the timestamp. The street, city and code fields must be persisted in a
second table called ADDRESS_TBL. The countryName and zipCode fields must be
stored in a table called COUNTRY_TBL.
8
1.3 Implementation of JPA annotations
Example
Create a web application that will perform CRUD (Create Read Update Delete)
operations on a classlist. The classlist contains students. A student has an id, name,
surname, and gender. The id is automatically generated by the persistence provider.
The table below shows all the fields of a student and the constraints that must be
applied to each field.
Field Constraint
id Primary key. Must be automatically generated by the persistence provider.
name Must be a string. Can be nullable. The maximum length is 20.
surname Must be a string. Can be nullable. The maximum length is 20.
gender Must be a string of length 1. Can be nullable. The maximum length is 1.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
9
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
10
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
11
Part B – Connect the database to the application server.
Click on the Services tab.
12
Right-click on the server and select View Domain Admin Console.
13
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
14
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
15
✓ Save the changes by clicking the Save button.
✓ Check if the created connection pool is working. Do this by clicking the Ping
button.
16
Confirm that the resource points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
17
Part C – Create an entity.
Create an EJB project called PersonEJBModule.
18
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
19
Fill-in the form.
20
Click Next.
21
Under Data Source, select jdbc/_default.
22
Click Finish.
23
24
25
Create business code (CRUD operations) for the entity. Perform the following steps:
✓ Right-click on the project and select New | Other.
26
✓ Click Next.
27
✓ Select za.ac.tut.entities under Available Entity Classes.
28
✓ Click Add.
29
✓ Click Next.
30
✓ Modify the package name to za.ac.tut.bl, where bl stands for business logic.
Also select Local interface.
31
▪ AbstractFacade.
32
33
▪ PersonFacadeLocal.
34
✓ Clean and build the EJB project.
35
Edit the index.html page.
36
37
Create add_person.jsp file.
38
Create the edit_person.jsp file.
39
Create the search_person.jsp file.
40
Create the get_list.jsp file.
41
Create the get_partial_list.jsp file.
42
43
Create the remove_person.jsp file.
44
Create the get_list_size.jsp file.
45
Add the PersonEJBModule.jar file to the library of PersonWebApp.
46
Create the AddPersonServlet.java file.
47
Create the EditPersonServlet.java file.
48
49
Create the SearchPersonServlet.java file.
50
Create the GetListServlet.java file.
51
Create the GetPartialListServlet.java file.
52
Create the RemovePersonServlet.java file.
53
Create the GetListSizeServlet.java file.
54
Create the add_person_outcome.jsp file.
55
Create the search_person_outcome.jsp file.
56
57
Create the search_person_outcome.jsp file.
58
Create the get_partial_list_outcome.jsp file.
59
Create the remove_person_outcome.jsp file.
60
View the complete project structure of PersonWebApp.
61
62
Compile the project.
63
Part E – Run the web application.
Launch the application.
64
Fill in the form.
65
Add four more people into the database. To view the records in the database, do the
following:
✓ Select the Services tab.
✓ Expand Databases.
66
✓ Right-click on ClassListDB and select Connect.
67
✓ Expand the database.
68
✓ Right-click on Person_TBL and select View Data.
69
✓ Click on the button.
70
✓ Click on the button.
71
✓ Enter 4 for ID, and Baloyi as the new surname.
72
Search for a person.
✓ Select option 3 on the menu page.
73
✓ Enter ID number 5.
74
View partial list.
✓ Select option 5 on the menu page.
✓ Enter 1 and 3.
75
✓ Click on the button.
76
✓ Enter ID number 3.
77
✓ View all the records.
78
1.3.2 Using basic annotations and secondary tables.
Example
Create a web application that will perform part of the CRUD (Create Read Update
Delete) operations on a list of bank account holders. Specifically we want the
application to be able to create, search and retrieve the list. An account holder has
an id, full name, street, city, code, cell number, email address, balance, and
creation date attributes. The street, city and code attributes of each account holder
79
must be kept in a table of its own called Address. The cell numbers and email
addresses of account holders must be kept another secondary table called Contacts.
The table below shows all the fields of an account holder and the applicable constraints
for each field.
Field Constraint
id Primary key.
fullName Must be a string. Cannot be nullable. The maximum length is 50.
street Must be a string. Can be nullable. The maximum length is 20.
city Must be a string. Can be nullable. The maximum length is 20.
code Must be a string. Can be nullable. The maximum length is 20.
cellNo Must be a string. Can be nullable. The maximum length is 20.
emailAddress Must be a string. Can be nullable. The maximum length is 20.
balance Must be a double. Cannot be nullable.
creationDate Must be a Date.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
80
Click on the Services tab.
81
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
82
Right-click on the database and select Connect.
83
Right-click on the server and select View Domain Admin Console.
84
Modify the Connection pool to include the AccountHoldersDB.
✓ Click on JDBC Connection Pools.
85
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
86
✓ Save the changes by clicking the Save button.
87
Confirm that the data source (resource) points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
88
Part C – Create an entity.
Create an EJB project called AccountHolderEJBModule.
89
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
90
Fill-in the form.
91
Click Next.
92
Under Data Source, select jdbc/_default.
Click Finish.
93
94
95
96
View the persistence.xml file.
Create business code (Create account holder, search for account holder and display
all account holders) for the entity. Perform the following steps:
✓ Right-click on the project and select New | Other.
97
✓ Under Categories, select Enterprise JavaBeans. Under File Types select
Session Beans for Entity Classes.
98
✓ Click Next.
99
✓ Select za.ac.tut.entities.AccountHolder under Available Entity Classes and
click Add.
100
✓ Click Next.
101
✓ Modify the package name to za.ac.tut.ejb.bl, where bl stands for business
logic. Also select Local interface.
102
▪ AbstractFacade.
103
▪ AccountHolderFacadeLocal.
104
✓ Remove all the other interface methods except create, find and findAll.
105
✓ Clean and build the EJB project.
106
Part D – Create a web client project.
Create a web client project called AccountHolderWebApp.
107
Edit the index.html page.
108
Create the menu.jsp file.
109
110
Create the search_accountholder.jsp file.
111
Create the get_accountholders.jsp file.
112
Add the AccountHolderEJBModule.jar file to the library of AccountHolderWebApp.
113
114
Create the AddAccountHolderServlet.java file.
115
Create the SearchAccountHolderServlet.java file.
116
Create the GetAccountHoldersServlet.java file.
117
Create the search_accountholder_outcome.jsp file.
118
Create the search_accountholder_outcome.jsp file.
119
120
121
View the complete project structure of AccountHolderWebApp.
122
123
Compile the project.
124
Part E – Run the web application.
Launch the application.
125
Add an account holder.
✓ Click on the first link.
126
✓ Click on the add button.
127
✓ Add four more account holders into the database. View the records in the
database.
128
Search for an account holder.
✓ Click on the second link.
129
✓ Enter ID number 111.
130
Display all the account holders.
✓ Click on the third link.
131
132
133
1.3.3 Using basic annotations and collections.
Example
Create a web application that will perform part of the CRUD (Create Read Update
Delete) operations on a list of employees. Specifically we want the application to be
able to create and read the list. An employee has an id, two contact numbers which is
the employee’s cell number and that of a close relative. The table below shows all the
fields of an employee and the applicable constraints to each field.
Field Constraint
id Primary key.
contactNos Must be a list of strings.
creationDate Must be a Date. Can be nullable. The maximum length is 20.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
134
Part A - Create a database
Launch NetBeans.
135
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
136
Part B – Connect the database to the application server.
Click on the Services tab.
137
Right-click on the server and select View Domain Admin Console.
138
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
139
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
140
✓ Save the changes by clicking the Save button.
141
Confirm that the data source (resource) points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
142
Part C – Create an entity.
Create an EJB project called EmployeeEJBModule.
143
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
144
Fill-in the form.
145
Click Next.
146
Under Data Source, select jdbc/_default.
Click Finish.
147
148
149
View the persistence.xml file.
Create business code (Create employee and search for employee) for the entity.
Perform the following steps:
✓ Right-click on the project and select New | Other. Under Categories, select
Enterprise JavaBeans. Under File Types select Session Beans for Entity
Classes.
150
✓ Click Next.
151
✓ Select za.ac.tut.entities.Employee under Available Entity Classes and click
Add.
152
✓ Click Next.
153
✓ Click Finish. View created files.
▪ EmployeeFacade.
154
▪ AbstractFacade.
155
▪ EmployeeFacadeLocal.
156
✓ Remove all the other interface methods except create and find.
157
✓ Clean and build the EJB project.
158
Part D – Create a web client project.
Create a web client project called EmployeeWebApp.
159
Edit the index.html page.
160
Create the menu.jsp file.
161
Create the find_employee.jsp file.
162
163
Add the EmployeeEJBModule.jar file to the library of EmployeeWebApp.
164
Create the AddEmployeeServlet.java file.
165
Create the FindEmployeeServlet.java file.
166
Create the find_employee_outcome.jsp file.
167
View the complete project structure of EmployeeWebApp.
168
169
Compile the project.
170
Part E – Run the web application.
Launch the application.
171
Add an employee.
✓ Click on the first link.
172
✓ Click on the add button.
173
✓ Add four more employees into the database. View the records in the database.
174
✓ Enter ID number 333.
175
1.3.4 Using basic annotations and maps
Example
Create a web application that will perform part of the CRUD (Create Read Update
Delete) operations on a list of subjects. Specifically we want the application to be able
to create and read the list. A subject has a code and a name. The table below shows
all the fields of an employee and the applicable constraints to each field.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
176
Part A - Create a database
Launch NetBeans.
177
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
178
Part B – Connect the database to the application server.
Click on the Services tab.
179
Right-click on the server and select View Domain Admin Console.
180
Under Common Tasks panel, expand JDBC.
181
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
182
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
183
✓ Save the changes by clicking the Save button.
184
Confirm that the data source (resource) points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
185
Part C – Create an entity.
Create an EJB project called SubjectEJBModule.
186
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
187
Fill-in the form.
188
Click Next.
189
Under Data Source, select jdbc/_default.
190
Click Finish.
191
192
View the persistence.xml file.
193
Create business code (Create employee and search for employee) for the entity.
Perform the following steps:
✓ Right-click on the project and select New | Other.
194
✓ Click Next.
195
✓ Select za.ac.tut.entities.Subject under Available Entity Classes and click
Add.
✓ Click Next.
196
✓ Modify the package name to za.ac.tut.ejb.bl, where bl stands for business
logic. Also select Local interface.
197
▪ AbstractFacade.
198
199
▪ SubjectFacadeLocal.
200
✓ Remove all the other interface methods except create and findAll.
201
✓ Clean and build the EJB project.
202
Part D – Create a web client project.
Create a web client project called SubjectWebApp.
203
Edit the index.html page.
204
Create the menu.jsp file.
205
Create add_subject.jsp file.
206
Create the get_subjects.jsp file.
207
Add the SubjectEJBModule.jar file to the library of SubjectWebApp.
208
Create the AddSubjectServlet.java file.
209
210
Create the GetSubjectsServlet.java file.
211
Create the get_subjects_outcome.jsp file.
212
213
View the complete project structure of EmployeeWebApp.
214
Compile the project.
215
Part E – Run the web application.
Launch the application.
216
Add an employee.
✓ Click on the first link.
217
✓ Click on the add button.
218
✓ Add four more employees into the database. View the records in the database.
219
✓ Enter ID number 333.
220
1.4 Mapping relationships
JPA also supports the mapping of relationships between tables. There four
relationships that are normally used, namely;
• OneToOne;
• OneToMany;
• ManyToOne; and
• ManyToMany.
JPA uses annotations to map these relationships. In our case, we are going to confine
ourselves to two annotations, @OneToOne and @OneToMany.
1.4.1 OneToOne
Talking objects wise, you have one class containing an instance of another class. This
means you have a container class which serves as the parent and the contained class
which serves as a child.
Example
Create a web application that will perform some of the CRUD (Create Read Update
Delete) operations on books. A book has an isbn, title, author, publication date and
price. An author has a name, surname and email address.
BOOK_TBL
Field Constraint
isbn Primary key.
title Must be a string. Cannot be nullable. The maximum length is 20.
author Must be a contained instance. Must have a reference to the child class called author.
publicationDate Must be a Date. Cannot be nullable.
221
price Must be a Double. Cannot be nullable.
creationDate The timestamp.
AUTHOR_TBL
Field Constraint
id Primary key. Must be automatically generated by the persistence provider.
name Must be a string. Cannot be nullable. The maximum length is 50.
surname Must be a string. Cannot be nullable. The maximum length is 50.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
222
Expand the Databases option.
223
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
224
Right-click on the database and select Connect.
225
Start the server.
226
Under Common Tasks panel, expand JDBC.
227
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
228
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
229
✓ Save the changes by clicking the Save button.
✓ Check if the created connection pool is working. Do this by clicking the Ping
button.
230
Confirm that the resource points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
231
Part C – Create an entity.
Create an EJB project called BooksEJBModule.
232
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
233
Fill-in the form.
234
Click Next.
235
Under Data Source, select jdbc/_default.
236
Click Finish.
237
238
239
Right-click on the project and select New | Entity Class
240
Click Finish.
241
242
243
244
View the persistence.xml file.
Create business code (CRUD operations) for the entity. Perform the following steps:
✓ Right-click on the project and select New | Other.
245
✓ Under Categories, select Enterprise JavaBeans. Under File Types select
Session Beans for Entity Classes.
✓ Click Next.
246
✓ Select all the entities under Available Entity Classes.
247
✓ Click Add.
248
✓ Click Next.
249
✓ Click Finish. View created files.
▪ AuthorFacade.
250
▪ BookFacade
251
▪ AbstractFacade.
252
253
▪ AuthorPersonFacadeLocal.
254
▪ BookFacadeLocal.
255
✓ Clean and build the EJB project.
256
Part D – Create a web client project.
Create a web client project called BookWebApp.
257
Edit the index.html page.
258
Create the menu.jsp file.
259
Create add_book.jsp file.
260
Create the get_books.jsp file.
261
Add the BookEJBModule.jar file to the library of BookWebApp.
262
Create the AddBookServlet.java file.
263
Create the GetBooksServlet.java file.
264
Create the add_book_outcome.jsp file.
265
266
Create the get_books_outcome.jsp file.
267
268
View the complete project structure of BookWebApp.
269
Compile the project.
270
Part E – Run the web application.
Launch the application.
Add a book.
✓ Click on the first link.
271
✓ Fill in the form.
272
Add four more books. View all the books.
✓ Click on the second link.
273
274
View the records in the database.
275
1.4.2 One-to-many
Example
Create a web application that will perform some of the CRUD (Create Read Update
Delete) operations on customers. A customer has a name, surname, and many
contact numbers. A contact has a value.
CUSTOMER_TBL
Field Description Constraint
id The customer id. Primary key. The customer id.
name The name of a customer. Must be a string. Cannot be nullable. The maximum
length is 20.
surname The surname of a customer. Must be a contained instance. Must have a reference
to the child class called author.
contacts The list of contacts. Must be a Date. Cannot be nullable.
creationDate The creation date. The timestamp.
CONTACT_TBL
Field Description Constraint
id The customer account number. Primary key. The customer id.
cellNo The cell number. Must be a string. Cannot be nullable. The maximum
length is 20.
Solution approach
The solution to this problem is going to be done in five parts, namely:
276
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
277
Right-click on Java DB and select Create Database.
278
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
279
Part B – Connect the database to the application server.
Click on the Services tab.
280
Start the server.
281
Right-click on the server and select View Domain Admin Console.
282
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
283
✓ Click on Add Property and add a url property with the following value:
284
✓ Check if the created connection pool is working. Do this by clicking the Ping
button.
285
Take note of the purpose of JDBC Resources. It is said:
”JDBC resources provide applications with a means to connect to a database.”
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
286
Right-click on the project and select New | Other.
287
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
288
Fill-in the form.
289
Click Next.
290
Under Data Source, select jdbc/_default.
291
292
Click Finish.
293
294
Right-click on the project and select New | Entity Class
295
Click Finish.
296
297
298
View the persistence.xml file.
299
Create business code (CRUD operations) for the entity. Perform the following steps:
✓ Right-click on the project and select New | Other.
300
✓ Click Next.
301
✓ Select all the entities under Available Entity Classes.
302
✓ Click Add.
303
✓ Click Next.
304
✓ Modify the package name to za.ac.tut.ejb.bl, where bl stands for business
logic. Also select Local interface.
305
▪ CustomerFacade
306
▪ AbstractFacade.
307
308
▪ ContactFacadeLocal.
▪ CustomerFacadeLocal.
309
310
✓ Clean and build the EJB project.
311
Part D – Create a web client project.
Create a web client project called CustomerWebApp.
312
Create the menu.jsp file.
313
Create add_customer.jsp file.
314
Create the get_customers.jsp file.
315
Add the CustomersEJBModule.jar file to the library of CustomerWebApp.
316
317
Create the AddCustomerServlet.java file.
318
Create the GetCustomersServlet.java file.
319
Create the get_customers_outcome.jsp file.
320
321
View the complete project structure of CustomerWebApp.
322
Compile the project.
323
Part E – Run the web application.
Launch the application.
324
Add a customer.
✓ Click on the first link.
325
Click on the add button.
326
Click on the button.
327
328
View the records in the database.
✓ View structure
329
Contents of the COSTUMER
330
1.5 Inheritance and JPA
Inheritance is a form of software reuse that allows a new class to be created from an
existing one. The new class is called a subclass and old one a superclass.
Consequently, the subclass possesses both the form and functionality of the
superclass. By form we mean type, the subclass becomes the type of the superclass.
By functionality we mean capability, the things that the subclass is capable of doing.
So the subclass assumes or inherits all the methods possessed by the superclass.
The subclass doesn’t have to code the inherited methods from scratch, but can
override them, that is change the inherited implementation
So inheritance describes the “is-a” relationship existing between two classes. We say
a new class “is-a” type of the old class. An example could be a Student who “is-a” a
Person. Another example is an Orange which “is-a” Fruit.
331
Let us have a look at each of the strategies.
This is a default strategy. Using this strategy, a single table is created for the hierarchy.
All the attributes of the superclass and subclasses are placed or mapped to a single
table.
The root class can be annotated with the @Inheritance annotation. If the annotation
is not explicitly written, the default inheritance strategy applied is the single table per
class hierarchy. Let us take an example.
Example
Create a web application to represent a Shape. We have two shapes, a Parallelogram
and a Rectangle. A Parallelogram has a base and a height, and a Rectangle has a
length and a width. The area of Parallelogram can be calculated as base * height
whilst that of a Rectangle can be calculated as length * width. Both shapes have an
extra attribute called isBig, which tells whether a shape wis big or not. The inheritance
class hierarchy can be represented as follows:
za.ac.tut.entities.Shape
- isBig:Boolean
za.ac.tut.entities.Rectangle
- width: int za.ac.tut.entities.Parallelogram
The equivalent table structure for the above hierarchy can be represented as follows:
SHAPE
FIELD DATA TYPE CONSTRAINT
ID INTEGER PRIMARY KEY
ISBIG BOOLEAN NULLABLE=TRUE
332
WIDTH INTEGER NULLABLE=TRUE
LENGTH INTEGER NULLABLE = TRUE
BASE INTEGER NULLABLE = TRUE
HEIGHT INTEGER NULLABLE = TRUE
As can be seen, all the attributes of the classes are put in a single table. Let us do the
actual coding.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
333
Expand the Databases option.
334
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
335
Right-click on the database and select Connect.
336
Part B – Connect the database to the application server.
Click on the Services tab.
337
Right-click on the server and select View Domain Admin Console.
338
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
339
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
340
✓ Save the changes by clicking the Save button.
✓ Check if the created connection pool is working. Do this by clicking the Ping
button.
341
Confirm that the resource points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
342
Part C – Create an entity.
Create an EJB project called ShapesEJBModuleV1.
343
Under Categories select Persistence, and under File Types select Entity Class.
Click Next.
344
Fill-in the form.
345
Click Next.
346
Under Data Source, select jdbc/_default.
347
Click Finish.
348
349
350
Create a Rectangle sub entity.
351
352
Create a Parallelogram sub entity.
353
354
View the persistence.xml file.
Create business code (CRUD operations) for the entity. Perform the following steps:
✓ Right-click on the project and select New | Other.
355
✓ Under Categories, select Enterprise JavaBeans. Under File Types select
Session Beans for Entity Classes.
✓ Click Next.
356
✓ Select all the entities under Available Entity Classes.
357
✓ Click Add.
358
✓ Click Next.
360
▪ RectangleFacade
361
▪ ShapeFacade
362
▪ AbstractFacade.
363
▪ ParallelogramFacadeLocal
364
▪ RectangleFacadeLocal.
365
▪ ShapeFacadeLocal.
366
✓ Clean and build the EJB project.
367
368
Part D – Create a web client project.
Create a web client project called BookWebApp.
369
Create the menu.jsp file.
370
371
372
Create the get_shapes.jsp file.
373
Add the ShapesEJBModuleV2.jar file to the library of ShapesWebAppV2.
374
Create the AddShapeServlet.java file.
375
Create the GetShapesServlet.java file.
376
Create the add_book_outcome.jsp file.
377
Create the get_shapes_outcome.jsp file.
378
379
380
View the complete project structure of ShapesWebAppV2.
381
Deploy the project.
382
Part E – Run the web application.
Launch the application.
383
Add shape book.
✓ Click on the first link.
384
✓ Fill in the form.
385
Click on the add button.
386
✓ Click on the button.
387
View the structure of the database.
388
Contents of the PARALLELOGRAM table.
When using this strategy, each entity in the hierarchy is mapped to its own table. The
main table is mapped to the root entity. The main table will mainly contain the primary
key, discriminator column and attributes defined in the root entity.
The sub-entities are mapped to their own tables. In those tables we find references to
the primary key defined in the main table, the fields defined in the respective sub-
entities, with no reference to inherited fields.
389
To define a Joined-subclass strategy, we use the InheritanceType.JOINED value
inside the @Inheritance annotation. For example we have something as follows:
Example
Create a web application to represent a Shape. We have two shapes, a Parallelogram
and a Rectangle. A Parallelogram has a base and a height, and a Rectangle has a
length and a width. The area of Parallelogram can be calculated as base * height
whilst that of a Rectangle can be calculated as length * width. Both shapes have an
additional attribute called isBig which signals whether a shape is big or not. The
inheritance class hierarchy can be represented as follows:
za.ac.tut.entities.Shape
- isBig:Boolean
za.ac.tut.entities.Rectangle
za.ac.tut.entities.Parallelogram
- width: int
- length: int - base: int
- height: int
The equivalent table structure for the above hierarchy will be as follows:
SHAPE
FIELD DATA TYPE CONSTRAINT
ID INTEGER PRIMARY KEY
ISBIG BOOLEAN NULLABLE=TRUE
390
WIDTH INTEGER NULLABLE=TRUE
LENGTH INTEGER NULLABLE = TRUE
BASE INTEGER NULLABLE = TRUE
HEIGHT INTEGER NULLABLE = TRUE
As can be seen, all the attributes of the classes are put in a single table. Let us do the
actual coding.
Solution approach
The solution to this problem is going to be done in five parts, namely:
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
391
Expand the Databases option.
392
Fill-in the form. I made the password to be 123.
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
393
Right-click on the database and select Connect.
394
Part B – Connect the database to the application server.
Click on the Services tab.
395
Right-click on the server and select View Domain Admin Console.
396
Under Common Tasks panel, expand JDBC.
397
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
398
✓ Save the changes by clicking the Save button.
✓ Check if the created connection pool is working. Do this by clicking the Ping
button.
399
Confirm that the resource points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
400
Part C – Create an entity.
Create an EJB project called ShapesEJBModuleV2.
401
402
403
Create a sub entity called Parallelogram.
404
405
Create a Rectangle sub entity.
406
407
View the persistence.xml file.
408
▪ RectangleFacade
▪ ShapeFacade
409
▪ AbstractFacade.
410
411
▪ ParallelogramFacadeLocal
412
▪ RectangleFacadeLocal.
▪ ShapeFacadeLocal.
413
✓ Clean and build the EJB project.
414
415
Part D – Create a web client project.
Create a web client project called ShapesWebAppV2.
416
Create the menu.jsp file.
417
Create add_shape.jsp file.
418
Create the get_shapes.jsp file.
419
420
Add the ShapesEJBModuleV2.jar file to the library of ShapesWebApp.
421
Create the AddShapeServlet.java file.
422
Create add_shape_outcome.jsp file.
423
Create GetShapesServlet.java file.
424
425
426
Part E – Run the web application.
Launch the application.
427
1.5.3 Table per concrete class strategy
When using this strategy, each entity in the hierarchy is mapped to its own table. This
is similar to the the Joined-subclass strategy. The only difference is that the attributes
of the superclass will be repeated in the tables of the subclasses.
Example
Create a web application to represent a Shape. We have two shapes, a Parallelogram
and a Rectangle. A Parallelogram has a base and a height, and a Rectangle has a
length and a width. The area of Parallelogram can be calculated as base * height
whilst that of a Rectangle can be calculated as length * width. The inheritance class
hierarchy can be represented as follows:
za.ac.tut.entities.Shape
- isBig:Boolean
za.ac.tut.entities.Rectangle
za.ac.tut.entities.Parallelogram
- width: int
- length: int - base: int
- height: int
Solution approach
The solution to this problem is going to be done in five parts, namely:
428
▪ Part A: we create a database.
▪ Part B: we stablish connection between the created database and GlassFish.
▪ Part C: we create an EJB module. The module will have an entity with business
logic.
▪ Part D: we create a client web application.
▪ Part E: we run the client web application.
429
Right-click on Java DB and select Create Database.
430
Click OK.
✓ An output message confirming that Derby has started and ready to accept
connections on port 1527 is shown.
✓ A database is created.
431
Part B – Connect the database to the application server.
Click on the Services tab.
432
Start the server.
433
Under Common Tasks panel, expand JDBC.
434
Modify the Connection pool to include the ClassListDB.
✓ Click on JDBC Connection Pools.
435
✓ Click on Additional Properties.
✓ Click on Add Property and add a url property with the following value:
436
✓ Save the changes by clicking the Save button.
✓ Check if the created connection pool is working. Do this by clicking the Ping
button.
437
Confirm that the resource points to the DerbyPool.
✓ Still under JDBC, click on JDBC Resources.
You can also see that the jdbc/_default resource is associated with the DerbyPool
Connection Pool.
438
Part C – Create an entity.
Create an EJB project called ShapesEJBModuleV3.
Create the Shape entity. Use the Table per concrete class strategy.
439
440
441
Create a sub entity called Parallelogram.
442
443
Create a Rectangle sub entity.
444
445
View the persistence.xml file.
446
▪ RectangleFacade
▪ ShapeFacade
447
▪ AbstractFacade.
448
449
▪ ParallelogramFacadeLocal
450
▪ RectangleFacadeLocal.
▪ ShapeFacadeLocal.
451
✓ Clean and build the EJB project.
452
453
Part D – Create a web client project.
Create a web client project called ShapesWebAppV3.
454
Create the menu.jsp file.
455
456
Create the get_shapes.jsp file.
457
Add the ShapesEJBModuleV3.jar file to the library of ShapesWebApp3.
458
459
Create the AddShapeServlet.java file.
460
Create the GetShapesServlet.java file.
461
Create the add_book_outcome.jsp file.
462
Create the get_shapes_outcome.jsp file.
463
464
465
View the complete project structure of ShapesWebAppV3.
466
Compile the project.
467
Part E – Run the web application.
Launch the application.
Add a shape.
✓ Click on the first link.
468
✓ Fill in the form.
469
Add four more shapes. View all the shapes.
✓ Click on the second link.
470
471
View the records in the database.
472
473
Contents of the SHAPE table.
474
1.6 DIY (Do It Yourself)
In this DIY we want you to develop web applications that use JPA.
Task #1
Create a database-driven web application that will perform CRUD (Create Read
Update Delete) operations on bank accounts. The application must allow a user to
perform the following tasks:
• Create an account.
• Search for an account.
• Display the details of all the accounts in the database.
• Edit some of the details of an account.
• Remove an account.
• Display the number of accounts stored in a database.
To do
Create such a web application.
475
Task #2
Lerato is a programming intern at WeDoWebApps company. The company
specializes in developing web apps that are conversational, fail-safe (handle
exceptions), personalized and database-driven for their clients. Mr Maluleke, a senior
developer at WeDoWebApps, has been assigned the responsibility of mentoring
Lerato. As his first task, Mr Maluleke gives Lerato an opportunity of creating a web
application for a client. The client is Ms Skosana, a teacher by profession.
Ms Skosana wants a personalized web application that will work with two roles,
teachers and students. Teachers must be able to perform the following task:
• Create a multiple choice test and store it in the database.
The work of the student must be stored in a database. By work we mean the questions
done, the answers of the student, the correct answers, and the percentage mark of
the student.
To do
Assuming that you are Lerato, create such a web application.
1.7 Conclusion
Thank you very much for having taken time to go through this chapter. Enjoy the rest
of the day and God bless you.
476