an eclipsejavaee6 postgresql
TRANSCRIPT
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
1/255
An Eclipse / GlassFish / Java EE 6 Tutorial
For whatever reason my programming blog got lost in binary space. Because of the popularity of thispage !"ve restore# in from a bac$up. ! probably won"t restore the rest of the site though.
%ersion &.' last up#ate# (ay )* )+&& , &&-&+
The content of this tutorial is still relevant but you may also consi#er my new open sourceAyt
JEE Tools a set of Eclipse plugins that greatly simplify the process of creating a Java Enterprise
application using the patterns outline# in this tutorial. ee theAyt JEE Tools home pagean#
especially the tutorial 01sing Ayt JEE Tools0.
&. Applicability
). 2ow to use the tutorial
*. Typographical conventions
'. Tools
3. 4reparing the wor$space
6. 4reparing the #atabase
5. The container proect 7EA8 proect9
:. 4urpose
;. teps in Eclipse
&+. The core logic 7EJB proect9
&&. Abstraction of #ata access 7Entity Access
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
2/255
&*. !nstantiation of Enterprise Java Beans
&'. EJB annotation
&3. =oo$up via J>?!
&6. @alling the bean as a
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
3/255
*). 8eferencing the J?B@ resource from the application
**. ?ata Transfer oterialiableEception
'6. Testing internal interfaces
'5. Testsuite
':.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
4/255
3&. !nsert an# 1p#ate
3). Eten#ing the ?atabase
3*. Eceptions
3'. !mplementing storeip79
33. !f it #oes not wor$
36. ava.sl.=yntaErrorEception- Table/%iew HE1E>@E" #oes not eist
35. 8esult has no i#
3:. %ali#ation
3;. %ali#ationEception
6+. pecifying constraints
6&. %ali#ation using interceptors
6). Testing the vali#ator
6*.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
5/255
5+. yn#ication Fee#s
5&. 8ealiing a fee# with 8?! @ustom 8esources
5'. Access via 8ET
53. The 8ET servlet
56. The 8ET #elegator
55. Eamples of 2TT4 traffic
5:. a##79
5;. country@ount79
:+. #ump@ountries79
:&. storeip79
:). inputtream79
:*. 4ostgre= as #atabase bac$en#
:'. !nstalling 4ostgre= an# creating a #atabase user
:3. @reating the #atabase
:6. 4ostgre= connection pool in GlassFish
:5. ?efinition of the #atasource in Eclipse
::. Entities
http://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-syndication-feedshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-realizing-a-feed-with-romehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-a-bug-in-eclipsehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-configuration-via-jndi-custom-resourceshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-access-via-resthttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-the-rest-servlethttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-the-rest-delegatorhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-examples-of-http-traffichttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-addhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-countrycounthttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-dumpcountrieshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-storeziphttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-inputstreamhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-postgresql-as-database-backendhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-installing-postgresql-and-creating-a-database-userhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-creating-the-databasehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-postgresql-connection-pool-in-glassfishhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-definition-of-the-datasource-in-eclipsehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-entitieshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-syndication-feedshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-realizing-a-feed-with-romehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-a-bug-in-eclipsehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-configuration-via-jndi-custom-resourceshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-access-via-resthttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-the-rest-servlethttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-the-rest-delegatorhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-examples-of-http-traffichttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-addhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-countrycounthttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-dumpcountrieshttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-storeziphttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-inputstreamhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-postgresql-as-database-backendhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-installing-postgresql-and-creating-a-database-userhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-creating-the-databasehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-postgresql-connection-pool-in-glassfishhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-definition-of-the-datasource-in-eclipsehttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-entities -
7/24/2019 An EclipseJavaEE6 PostgreSQL
6/255
:;. Access to 4ostgre= via =
;+. @onclusion
!n 0' , EuipmentI ! have committe# myself to using Eclipse an# the Java Enterprise E#ition as my
tools while in 03 , 4atterns An# =anguagesI !"ve #eclare# my highlevel goals for implementing a
net step of #esign patternbase# tools. >ow for a #eeper un#erstan#ing of #esign patterns you
first have to use them. This post in the form of a tutorial shows some very basic proect setups using
Eclipse an# GlassFish.
! am no epert in this fiel# some
important things may be missing so ust ta$e the following as a set of things that wor$ for me.
As ! am not immune to learning an# as ! am going the use these things a lot it is inevitable that my
un#erstan#ing of certain aspects will change. ! suppose that means ! will have to ma$e changes to
this post whenever it happens. !f ! ever #o so ! will post a short notice.
Applicability
This is a tutorial about using Eclipse an# the GlassFish v* Java application server to implement Java
EE 6 applications. ! will show how to use #ifferent Eclipse proect types for #ifferent purposes will
show how to #o manual tests an# how to implement automatic unit tests. Ce will not create a
complete application but more a vertical slice through an application. The i#ea is to ust touch all
relevant areas not to finish a proect.
http://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-access-to-postgresql-via-sslhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-conclusionhttp://programming.manessinger.com/2010/03/30/4-equipment/http://programming.manessinger.com/2010/04/04/5-patterns-and-languages/http://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-access-to-postgresql-via-sslhttp://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/#toc-conclusionhttp://programming.manessinger.com/2010/03/30/4-equipment/http://programming.manessinger.com/2010/04/04/5-patterns-and-languages/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
7/255
The tutorial assumes the eistence of a relational #atabase an# it concentrates on the Java
application use# as a bac$en#. 1sing JF or another serverbase# G1! framewor$ is #efinitely out
of scope.
How to use the tutorial
For your convenience an# for reference ! have ippe# the wor$space that ! have use# in these
eamples 7all but the .metadata#irectory9 an# uploa#e# it to my server. ou can #ownloa# it from
http-//manessinger.com/#ata/playgroun#.ip.These files reflect eactly what you are going to have
when you have complete# this tutorial. >o interme#iate steps are containe# in the archive. For the
best learning effect ! suggest that you #on"t use these sources but ust follow the tutorial step by
step. Eventually you will get to eactly that result.
ource listings in this tutorial can normally be ta$en by cut an# paste. There is only one instance of
an K(= file where you can"t #o it but in that instance ! eplicitly say so.
!f you #on"t type the program tets but instea# copy them by cut an# paste it is possible to complete
the tutorial in si to eight hours. ?epen#ing upon your familiarity with the topics covere# it may be
shorter or consi#erably longer.
Typographical conventions
!"m trying to use a little bit of semantic mar$up here. At the moment ! use the following conventions-
Term 1se# for terms normally only when they are intro#uce#
1! Element 1se# for user interface elements everything that refers to G1! elements
tet 1se# for names tets that you type in or that you get as fee#bac$ from the G1!
Tools
! use the GlassFish Tools Bun#le for Eclipse an# at the time of this writing it is version &.) release#
?ecember &5 )++;. This pac$age bun#les the Java EE 6 reference implementation with Eclipse
*.3.& an# J?L &.6. ! have installe# it on Cin#ows 5 in the #efault location @-MGlassFishTools
Bun#leForEclipse&.)
http://manessinger.com/data/playground.ziphttp://manessinger.com/data/playground.ziphttp://download.java.net/glassfish/eclipse/http://manessinger.com/data/playground.ziphttp://download.java.net/glassfish/eclipse/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
8/255
Chile Eclipse *.6 02eliosI has been release# an# is alrea#y supporte# by a new version of the
GlassFish plugin for Eclise there is still an annoying bug an# ! currently suggest that unless you
really really nee# 2elios you ust use the bun#le until the bug gets fie#. ee 05 , Eclipse *.6
02eliosI an# GlassFish *.+&I for #etails.
The #atabase isApache ?erby.This comes as part of the tools bun#le. !t has all the features of
0realI #atabases li$e
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
9/255
an EA8 is the artifact of an Enterprise Application 4roect basically a container proect that bun#les
collections of subproects into a single artifact.
Every time you open Eclipse it as$s you for the wor$space to use an# when you open Eclipse for
the first time or when you open Eclipse with a new wor$space name i.e. a wor$space that #oes not
yet eist 7for instance playgroun#9 you arrive at the welcome screen. >ot much to #o there only
some #ocumentation lin$s what you really want to #o is go on to the wor$bench.
!f it"s a new wor$space you"ll be in the 8esource 4erspective.
The 4erspective is another important concept in Eclipse. There are #ifferent perspectives for
#ifferent $in#s of wor$. There is a Java EE 4erspective for wor$ing with Java in an Enterprise E#ition
environment a ?atabase ?evelopment 4erspective for wor$ing with #atabases an# so on.
Each perspective is an arrangement of %iews. A %iew shows a particular aspect in a perspective.
ou have a treeli$e 4roect Eplorer view 7normally along the left e#ge of the Eclipse win#ow9 an
E#itor %iew on an open file a @onsole %iew showing console output li$e in a passive terminal a
ervers %iew listing the running servers an# giving access to server comman#s li$e tart an# top.
%iews can be tabbe# together in groups. !f something important happens in a view Eclipse
automatically ma$es it the top tab in a tabbe# group.
The 8esource perspective is a general perspective for accessing proect resources. Ce nee# two
other perspectives Java EE an# ?atabase ?evelopment.
1se Cin#ow / ow you will have
two buttons in the upper right toolbar one labele# Java EE an# the other 8esource. Each of these
has a contet menu 7mouse right9 an# you can #rag one button upon the other to change positions.
Try that an# then choose @lose from the contet menu of the 8esource perspective. Ce #on"t nee#
it any more. !n the same way you shoul# open the ?atabase ?evelopment perspective. Then switch
bac$ to the Java EE perspective.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
10/255
ou may or may not have a server #efinition in the ervers view an# you may not even see a
ervers view at all. !t shoul# be in the tabbe# pane at the bottom. !f not use Cin#ow / how %iew /
ervers or if it"s not #irectly in the menu use Cin#ow / how %iew / ew / erver. Just follow the screenshots. !f you #on"t use
theGlassFish Tools Bun#le for Eclipse you may have to #efine a new server runtime first either
from the lin$ on the first page of the >ew erver wiar# or from the menu bar via Cin#ow /
4references / erver / 8untime Environments / A##.
>ow that we have a server we nee# one more view that we"ll use freuently an# that is not visible
by #efault.
Ce use J1nitfor unit tests. J1nit comes bun#le# with Eclipse an# of course there is a J1nit view for
starting tests an# viewing results. !n the JEE perspective its #efault location is a ta# aw$war# thus
we will change it. !f it is visible at all it is in the bottom pane where you also fin# the ervers view. !f
you #on"t see it open it with Cin#ow / how %iew / ow ta$e the tab an# #rag it onto the tab of the 4roect Eplorer in the left part of Eclipse. Again you
can change or#ers by #ragging the tabs onto each other. (a$e sure the 4roect Eplorer is visible
that"s what we use most of the time.
http://download.java.net/glassfish/eclipse/http://download.java.net/glassfish/eclipse/http://www.junit.org/http://www.junit.org/http://download.java.net/glassfish/eclipse/http://www.junit.org/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
11/255
Preparing the database
This is neither about obectrelational mapping nor is it a meaningful sample application. ! still want
at least two or three classes with foreign $ey relationships thus we will use a classic master/#etail
relation- a table of countries an# a secon# table of cities with cities being locate# in countries. ew an# first have to select name an# #atabase type 7?erby9.
http://db.apache.org/derby/http://db.apache.org/derby/http://programming.manessinger.com/2010/03/30/4-equipment/http://db.apache.org/derby/http://programming.manessinger.com/2010/03/30/4-equipment/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
12/255
Ce clic$ >et an# now have to specify the new connection"s properties. ! use coo$boo$#b as
#atabase name 7the name on the previous page was for #isplay9 an# specify a user coo$boo$user
with passwor# coo$boo$. 1se whatever you li$e. Ce will use this #atabase a lot there won"t ever be
anything of value in it thus we can safely tic$ ave passwor#. !f you #on"t feel comfortable saving
passwor#s in a #evelopment tool you have my respect ust #on"t #o it but in any case try the Test
@onnection button once. ou will be confirme# with a message bo that 4ing succee#e#. @lic$
Finish an# we"re #one.
?erby is mo#ele# after the big guys thus we have not only #atabases we have
schema as well. =oo$s li$e ow that we have a #atabase we create the tables. ?erby has automatically create# a schema for
our user cookbookuser7though you can"t yet see it9. !n that schema we create two tables
@T8 an# @!T the primary $eys an# the constraints.
!n or#er to #o this select the new #atabase an# from its contet menu choose ow copy the
following tet an# paste it into the = win#ow. Then rightclic$ in the win#ow an# choose Eecute
All.
--
-- Set up database schema
--
CREATE TABLE COUNTRY (
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
13/255
I INTE!ER !ENERATE AL"AYS AS IENTITY NOT NULL#
NA$E %ARC&AR(')
)*
ALTER TABLE COUNTRY A CONSTRAINT COUNTRY+,RI$ARY+EY ,RI$ARY EY (I)*
CREATE UNIUE INE/ COUNTRY+NA$E+I/ ON COUNTRY(NA$E)*
CREATE TABLE CITY (
I INTE!ER !ENERATE AL"AYS AS IENTITY NOT NULL#
COUNTRY+I INTE!ER NOT NULL#
NA$E %ARC&AR(')
)*
ALTER TABLE CITY A CONSTRAINT CITY+,RI$ARY+EY ,RI$ARY EY (I)*
ALTER TABLE CITY A CONSTRAINT CITY+0OREI!NEY+COUNTRY+I 0OREI!N EY
(COUNTRY+I)
RE0ERENCES COUNTRY (I)*
CREATE UNIUE INE/ CITY+NA$E+I/ ON CITY(NA$E)*
--
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
14/255
-- I12t2a324e 52th some 6a3ues
--
INSERT INTO COUNTRY (NA$E) %ALUES (7Austr2a7)*
INSERT INTO COUNTRY (NA$E) %ALUES (7Ita387)*
INSERT INTO COUNTRY (NA$E) %ALUES (7USA7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Austr2a7)# 7!ra47)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Austr2a7)# 7L2147)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Austr2a7)# 7Sa34bur:7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Austr2a7)# 7"2e17)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Ita387)# 7Bo3o:1a7)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
15/255
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Ita387)# 702re14e7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Ita387)# 7Roma7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7Ita387)# 7%e1e42a7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7USA7)# 7At3a1ta7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7USA7)# 7Los A1:e3es7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7USA7)# 7Ne5 York7)*
INSERT INTO CITY (COUNTRY+I# NA$E)
%ALUES ((SELECT I 0RO$ COUNTRY "&ERE NA$E 9 7USA7)# 7"ash21:to17)*
This is the #ata we"ll wor$ with. >ow you can choose from the contet menu of ?atabase
@onnections / @oo$boo$ ?atabase / coo$boo$#b / chemas an# when you #rill #own you see a
new schema @
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
16/255
Chen you loo$ at the table #efinitions you see that primary $eys are #eclare# as
I INTE!ER !ENERATE AL"AYS AS IENTITY NOT NULL*
This is ?erby"s way of #eclaring automatically generate# $eys. !n other #atabases you woul# use
seuences. euence support is alrea#y in the current version &+.6 of ?erby but the GlassFish
Tools Bun#le for Eclipsestill comes with &+.3. !n reality this is not important here. Ce are only going
to use this as a playgroun#.
The container project (EAR project)
Purpose
There are #ifferent Eclipse proect types that can be use# with the JEE 6. !n the most fleible setup
you use a socalle# Enterprise Application 4roect also calle# an EA8 4roect after the artifact it
pro#uces an Enterprise Archive or EA8.
An EA8 proect is nothing but a container inten#e# to bun#le the artifacts of the containe# proects
along with any libraries that they use an# that are not alrea#y part of the Java Enterprise E#ition. Ce
always begin with an EA8 proect an# then we create those proects where we #o the actual wor$
a##ing each of them to the EA8. =ater for #eployment we can eport the EA8 proect as one single
EA8 file that contains all JA8s from the containe# proects.
To#ay an EA8 woul# not be strictly nee#e#. To#ay ?ynamic Ceb 4roects the proect type that
compiles to a CA8 7Ceb Application Archive9 also run un#er the control of an enterprise container
thus you can use them to create Enterprise Java Beans something that use# to nee# an EJB
proect. till ! prefer to have my EJBs in an EJB proect an# that wrappe# up in an EA8.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
17/255
From now on if not eplicitly state# otherwise we always assume that Eclipse is starte# the
?atabase eists GlassFish server an# ?erby #atabase are starte# an# the JEE perspective is
active.
!n the JEE perspective you have the 4roect Eplorer on the left si#e. !f you have
a fresh wor$space then the 4roect Eplorer will be empty. Either from the File menu or from the
4roect Eplorer contet menu choose >ew / Enterprise Application 4roect. This opens the >ew
EA8 Application 4roect #ialog.
!t is not so important what specific naming convention you have but it is useful to have one. (ine is
to have a name for the overall application here coo$boo$ an# then to suffi the proects with
something that tells about their type. Thus the EA8 proect is suffie# with EA8.
The core logic (E! project)
Purpose
Enterprise Java Beans 7EJB9 are really ust normal Java classes. @reate one with 1e5 $8Bea1()
an# you get ust a plain ol# Java obect 74
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
18/255
>ot only #oes the container manage #atasources for accessing #atabases it also han#les
transactions an# it can #o not only the simple case of han#ling local transactions it also han#les
an#/or coor#inates #istribute# transactions.
But again in or#er for all this to wor$ you have to run your beans un#er the control of an EJB
container.
EJBs come in three flavors- tateless ession Beans tateful ession Beans an# ingleton Beans.
!n the contet of this sample application we will loo$ at only one of them stateless session beans.
!n the Java Enterprise E#ition before version 3 entity persistence was han#le# by the Enterprise
E#ition @ontainer as well. This was calle# @ontainer (anage# 4ersistence 7@(49 an# although you
can still #o it that way 7in fact for compatibility you can still #o allthat te#ious an# verbose K(=
configuration stuff9 the new an# much simpler way is to use the Java 4ersistence A4! 7J4A9.
Chen you use J4A an Entity is again a simple Java class with getters an# setters for its fiel#s a
4
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
19/255
=anguage. This is very much li$e = an# if you $now = you alrea#y $now most of what"s to
learn.
till relational #atabases are not the only possible way to store #ata 7although a goo# one9 an#
= is not the only way to get at #ata. The core logic of your application is not about getting or
storing #ata it is about manipulating it. Thus it ma$es sense to encapsulate #ata access.
Tra#itionally Java has #one a goo# ob encapsulating #ata access ust thin$ of the ?ata Access
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
20/255
!n other wor#s we #esign our application as a set of interfaces an# we implement these interfaces
as tateless ession Beans. EJBs that we #on"t epose li$e our Entity Access
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
21/255
A toplevel invocation is a call from outsideof a container into an EJB running insideof a container.
@learly inection alone woul# not help us ever ma$ing toplevel calls.
Although we may get a new chain of containermanage# EJBs for every toplevel invocation 7at least
as long as we loo$ at tateless ession Beans9 the inection mechanism is static insofar as the
container can alrea#y chec$ for availability of all reference# types at #eployment time. Thus if you try
to inect a variable of a type that is not #efine# at the application server 7but may have been #efine#
in your #evelopment environment9 the Enterprise Application won"t even start.
%ookup via &'$
ometimes you nee# more fleibility. For instance you coul# have #ifferent beans implementing the
same interface an# at runtime you may want to #eci#e yourself which type of implementation youreally want. !n such a case you woul# #eci#e 7base# on input some calculations or an event9 upon
the name of the bean type you are intereste# in an# then you woul# loo$ it up via J>?! the Java
>aming an# ?irectory !nterface.
ou #o this by going through an I12t2a3Co1te>t ust li$e
$8I1ter=ace m8Bea1 9
($8I1ter=ace) I12t2a3Co1te>t.doLookup(
?@a6a:3oba3$8EAR$8Bea1s$8Bea1?
)*
This is a shortcut for
$8I1ter=ace m8Bea1 9
($8I1ter=ace) 1e5 I12t2a3Co1te>t().3ookup(
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
22/255
?@a6a:3oba3$8EAR$8Bea1s$8Bea1?
)*
The parameter of 3ookup()is a socalle# J>?! name an# since JEE 6 there is a stan#ar# for J>?!
names. The name use# here is a global J>?! name. !t is prefie# by ?@a6a:3oba3?followe# by a
path consisting of the name of the EA8 the name of a JA8 within the EA8 7both without etension9
followe# by the name of the bean class.
!f you nee# to loo$up a bean that implements more than one interface you nee# to specify an
interface as well. Given $8Bea1implements an interface com.m8compa18.$8I1ter=ace the
loo$up via the fully ualifie# global J>?! name woul# be
$8I1ter=ace m8Bea1 9
($8I1ter=ace) I12t2a3Co1te>t.doLookup(
?@a6a:3oba3$8EAR$8Bea1s$8Bea1com.m8compa18.$8I1ter=ace?
)*
!t gets even more complicate# when we want to call into a bean on another machine. !n such a case
we have to use the longer form instantiate the I12t2a3Co1te>tourselves an# pass a set of
properties into its constructor thereby telling the contet on which machine to begin the search. ou
will see an eample of that later.
Apart from loo$ing up EJBs #ynamically from within an EJB container there is another even more
important use of J>?! loo$ups an# that is the loo$up from outsi#e of the container. !n fact given that
it has access to all necessary libraries any Java class can loo$ up an EJB via J>?! an# the bean
instance that is returne# will have been instantiate# by the EJB container. Therfore J>?! loo$up is a
way to access EJBs from outsi#e of the container thus allowing us to ma$e toplevel calls.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
23/255
alling the bean as a S#AP web service
Chile J>?! loo$ups are not eactly complicate# there is another easy way to access ervice
Beans- we can simply annotate their class as web service. !f we #on"t care about the eact schema
of the C?= that gets generate# it is enough to use one simple annotation li$e this-
;State3ess
;"ebSer62ce
pub32c c3ass $8Bea1 D
...
ou see two annotations here. ;State3essmar$s this bean as a tateless ession Bean an#
;"ebSer62cecauses the application server to ma$e all public metho#s of this bean accessible as
web service calls. Any such metho# can be calle# from a o!nterface view are eually efficient. For tightly couple# beans that have no use outsi#e
the application local interfaces or the >o!nterface view are a#euate choices.
8emote interfaces can be calle# across applications from everywhere within the application server
as well as from outsi#e even from other hosts. There is more than one way to #eclare a business
http://www.soapui.org/http://www.soapui.org/http://www.soapui.org/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
24/255
interface but to#ay the normal way is to annotate the interface with either ;Loca3or ;Remote for
instance li$e this-
;Remote
pub32c 21ter=ace $8I1ter=ace D
pub32c 3o1: 1umberO=Ob@ects()*
From within the EJB container business interfaces are normally accesse# via inection. ou #eclare
a fiel# of such an interface type an# the container automatically inects a matching instance.
;E
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
25/255
&. 8eferencing an EJB from a servlet 7an therefore from a ?ynamic Ceb 4roect9 bun#le#
within the same EA8. From Java EE 6 the servlet is instantiate# by the EJB container therefore
the EJB can be inecte#.
). 8eferencing an EJB from eternally via its remote interface. Access is via
I12t2a3Co1te>t.doLookup(). houl# an access via @orba/!!
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
26/255
4lease ma$e sure that A## proect to an EA8 is chec$e#. Also please verify
that coo$boo$EA8 is selecte#. Eclipse will always preselect the EA8 that you create# last thus if
you #on"t chec$ you coul# a## your proect to the wrong EA8. !t has happene# to me
4age two of the wiar# is
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
27/255
client interfaces of EJBs 7automatically #one by Eclipse9
classes that are use# as parameters in interface metho#s
eceptions that are thrown by interface metho#s
reating a service bean
The net thing we want to #o is to create a service bean with a preliminary interface for our
application an# then to test that manually. Ce will use a remote interface for the bean an# we will
also allow access via the >o!nterface view. ?epen#ing on sie an# compleity of the application it
may be reasonable to use one service bean for the whole application one for each use case or
whatever ma$es sense to you but we will always use at least one.
!n Java we structure our classes by organiing them in pac$ages each
pac$age correspon#ing to a #irectory. This is not the most sophisticate# implementation of
namespaces but it"s easy an# it gets the ob #one. 4ac$age names are hierarchically structure#
normally consisting of a reverse# #omain name as prefi then a proect name an# finally whatever
structure you use within your proect.
From the contet menu of the EJB proect ! choose >ew / 4ac$age. ! accept the #efault source
fol#er an# use as full pac$age name com.manessinger.coo$boo$.service. An# then now from the
contet menu of the new pac$age ! use >ew / ession Bean 7Java EE 69. ! call it @oo$boo$Bean
choose to give access to it by the >ointerface view an# via a remote interface. As name of the
remote interface ! use @oo$boo$!nterface. The #efault woul# have been CookbookBea1Remote but
! #on"t li$e to have the name of the interface reveal its locality. 8emote of local what ! want to name
is functionality.
The result is the following file 7reformatte# an# comments strippe#9-
packa:e com.ma1ess21:er.cookbook.ser62ce*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
28/255
2mport @a6a>[email protected]*
2mport @a6a>[email protected]*
;Loca3Bea1
;State3ess
pub32c c3ass CookbookBea1 2mp3eme1ts CookbookI1ter=ace D
pub32c CookbookBea1() D
This bean has two annotations- ;Loca3Bea1means that we can access it via the >o!nterface view
while ;State3ess#eclares it a tateless ession Bean.
1pon inspection we fin# out that CookbookI1ter=acehas not been create# in the EJB proect but
in the client proect instea#. !t is in the same pac$age though an# the pac$age has also been
create# automatically in the client proect. Thus no 2mportof the interface is necessary.
packa:e com.ma1ess21:er.cookbook.ser62ce*
2mport @a6a>[email protected]*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
29/255
;Remote
pub32c 21ter=ace CookbookI1ter=ace D
>ow we have a service bean but no functionality at all. =et"s a## a metho# for instance one that
returns the number of countries in the #atabase. !t"s ust for testing but we may even en# up
nee#ing it in a real application. This metho# will be calle# from outsi#e thus it has to be #efine# in
the interface. =et"s a## the following metho# to the interface-
pub32c 3o1: cou1tr8Cou1t()*
As soon as we store the interface we notice that Eclipse shows an error in @oo$boo$Bean. The
class name is un#erline# with a re# wavy line an# when we move the mouse over the re# mar$ we
see a popup with the message The type @oo$boo$Bean must implement the inherite# abstract
metho# @oo$boo$!nterface.country@ount79.
The popup offers two socalle# uic$ Fies. They are possible changes that Eclipse offers to #o
automatically an# that have the potential to fi the problem. !n this case they are
&. A## unimplemente# metho#s
). (a$e type @oo$boo$Bean abstract
yntactically both solve the problem but of course what we want is to a## the metho#.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
30/255
!n this popup Eclipes offers the uic$ fies as lin$s but you coul# also set the tet curser on an error
mar$er an# press @trl&. This woul# have the same effect only there woul# not be a popup with
lin$s but a #rop#own menu instea#.
uic$ fies are etremely powerful in Eclipse an# you can use them in many situations when there"s
not even an error. @onsi#er for instance the following situation- ou want to call S8stem.:ete16()
a library metho# that returns a $apFStr21:# Str21:G. 2ow #o you #o thatD ou coul# simply write
$apFStr21:# Str21:G e16 9 S8stem.:ete16()*
?oing so you woul# probably see the wor# $apun#erline# as error an# by pressing @trl& you
woul# be offere# the uic$ fi to import @a6a.ut23.$ap. >ot ba# but the smart way to #o it is to
write only the righthan# si#e
S8stem.:ete16()*
This is a vali# but useless statement thus no error will be in#icate#. Chen you now press @trl&
Eclipse offers the uic$ fi Assign statement to new local variable. !f we choose that Eclipse not onlygenerates the map #eclaration on the lefthan# si#e it also imports @a6a.ut23.$apfor us.
orry for the long #igression but to $now this is so incre#ibly useful ! ust ha# to mention it
=et"s get on with our metho#. !n @oo$boo$Bean.ava Eclipse has inserte# a metho# stub
;O6err2de
pub32c 3o1: cou1tr8Cou1t() D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
31/255
TOO Auto-:e1erated method stub
retur1 *
an# we change it to
;O6err2de
pub32c 3o1: cou1tr8Cou1t() D
retur1 H* 0I/$E ca33 EAO method
There are two 0magicI $ewor#s for comments. Eclipse generate# TOO an# ! have change# it to
0I/$E. Eclipse provi#es mar$ers where these $eywor#s occur an# this way it is easy to fin# the
places where you have preliminary co#e that nee#s to be change# later. 0I/$Eis the stronger of the
two.
The generate# metho# result value of ero is an unluc$y choice because it is also the #efault value
for an uninitialie# long. ! li$e to see something more #istinctive thus the value &5. ou may also use
') or 666 if you li$e
*anual testing via +lass,ish web service tester
At this moment we have a service bean with a callable metho# but we have no way yet to actually
call it. First we have to ma$e the application run. Two things have to be #one-
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
32/255
!n the lower part of the Eclipse win#ow we choose the ervers view. 2ere
shoul# be a server entry with the label GlassFish v* Java EE 6 at localhost Ntoppe#O. From the
contet menu of the server we choose A## an# 8emove.
Ce get a win#ow with two boes on the left si#e the applications available for #eployment on the
server on the right si#e those that are currently #eploye#. !n the list of available applications you see
our EA8. Cith A## P or A## All PP you can move it to the right an# then press Finish.
>et if we ha# not alrea#y #one so we woul# have to start the server. ou #o that in the ervers
view either from the contet menu of the server or with the green start button on the right si#e.
tarting the server may ta$e up to a minute.
Btw currently there seems to be a problem with restarting the servers. !t eventually succee#s but
only after a long an# annoying timeout. Thus please #on"t restart always stop/start.
From this moment on the EJB coul# be calle#. !t"s only that the call woul# have to come from a Java
client using the client proect on its @=AQ4AT2. This is much too much effort nee#e# thus we ust
ma$e our bean a web service an# then we can call it via
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
33/255
2mport @a6a>.@5s."ebSer62ce*
;Loca3Bea1
;State3ess
;"ebSer62ce
pub32c c3ass CookbookBea1 2mp3eme1ts CookbookI1ter=ace D
pub32c CookbookBea1() D
;O6err2de
pub32c 3o1: cou1tr8Cou1t() D
retur1 H* 0I/$E ca33 EAO method
!f you store that change the application running in GlassFish is automatically up#ate#. This
automatic re#eployment wor$s most of the time it may fail though after maor refactorings. !f so ust
stop the server an# start it again 7#i# ! caution you against restartingD9.
GlassFish comes with a web application for a#ministration. !t"s calle# the A#ministration @onsole. !t
has its own port number an# which port that is this is our net ob to fin# out.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
34/255
There can be more than one GlassFish #omain on one machine a #omain actually being an
instance of the server with its own set of port numbers. To fin# out what port numbers our installation
uses we choose
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
35/255
>ote- shoul# you instea# get an internal error in the tester win#ow an# in the console log in Eclipse
a stac$ trace with something li$e the following tet in the mi##le
Caused b8 com.su1.>m3.5s.ut23.Ser62ceCo1=2:urat2o1Error
com.su1.>m3.5s.ap2.p2pe.Tra1sport,2pe0actor8
,ro62der
[email protected]:21e.br2d:e.tra1sport.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
36/255
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
37/255
The co#e generator inclu#e# with Eclipse allows us to let the generate# entities inherit from a class
or implement any number of interfaces.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
38/255
>ow the classes are visible in Eclipse at compile time but in or#er to ma$e them accessible when
running in GlassFish we nee# to put the JA8 file of the utility proect into the lib #irectory of the
EA8. Ce #o that in the 4roperties #ialog of the EA8 proect.
Then we create a pac$age com.manessinger.util.pa in the utility proect an# there we a## a class
E1t2t8 the base class for our entities-
packa:e com.ma1ess21:er.ut23.@pa*
pub32c abstract c3ass E1t2t8 D
pub32c stat2c boo3ea1 2sId(I1te:er 2d) D
retur1 (2d 9 1u33 2d G )*
pub32c boo3ea1 hasId() D
retur1 2sId(:etId())*
pub32c abstract I1te:er :etId()*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
39/255
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
40/255
Chen the #ialog opens it can be that Eclipse has no connection to the #atabase yet. !n that case
you can connect with a clic$ on the connection icon #irectly below the @onnection #rop#own menu.
Chen you are connecte# you can see a list of tables in the connecte# schema. @hec$ all tables that
you want to generate entities for an# press >et.
!n the following step you see the associations that Eclipse was able to #etect. Eclipse is fairly goo#
at it but of course this will only wor$ for reasonably crafte# #atabase schemas. !f you #on"t use
foreign $ey constraints an# not even name your fiel#s in a meaningful way then you"ll have to #o the
mapping yourself. !n my eperience what you nee# to change most often are the property names
i.e. the names that refer to the associations in Java. !n this trivial case Eclipse has #etecte# all there
was.
The net step is the #efinition of mapping #efaults. >ormally you will have only one strategy of
generating !?s an# that will apply to all tables. !n
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
41/255
!n the last step we can change the #efaults for tables an# even #own to each fiel#. Ce can rename
change #atatypes etc. 2ere we change the types of the generate# primary $eys 7i#9 from 21tto
I1te:er. 8emember to #o that for both tables.
2ere is the generate# co#e reformatte# to ma$e it more compact-
packa:e com.ma1ess21:er.cookbook.e1t2t8*
2mport @a6a.2o.Ser2a324ab3e*
2mport @a6a>.pers2ste1ce.P*
2mport @a6a.ut23.Set*
;E1t2t8
pub32c c3ass Cou1tr8 e>te1ds com.ma1ess21:[email protected] 2mp3eme1ts
Ser2a324ab3e D
pr26ate stat2c =21a3 3o1: ser2a3%ers2o1UI 9 HL*
;Id
;!e1erated%a3ue(strate:89!e1erat2o1T8pe.IENTITY)
pr26ate I1te:er 2d*
pr26ate Str21: 1ame*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
42/255
b2-d2rect2o1a3 ma18-to-o1e assoc2at2o1 to C2t8
;O1eTo$a18(mappedB89?cou1tr8?)
pr26ate SetFC2t8G c2t2es*
pub32c Cou1tr8() D
pub32c I1te:er :etId() D retur1 th2s.2d*
pub32c 6o2d setId(I1te:er 2d) D th2s.2d 9 2d*
pub32c Str21: :etName() D retur1 th2s.1ame*
pub32c 6o2d setName(Str21: 1ame) D th2s.1ame 9 1ame*
pub32c SetFC2t8G :etC2t2es() D retur1 th2s.c2t2es*
pub32c 6o2d setC2t2es(SetFC2t8G c2t2es) D th2s.c2t2es 9 c2t2es*
packa:e com.ma1ess21:er.cookbook.e1t2t8*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
43/255
2mport @a6a.2o.Ser2a324ab3e*
2mport @a6a>.pers2ste1ce.P*
;E1t2t8
pub32c c3ass C2t8 e>te1ds com.ma1ess21:[email protected] 2mp3eme1ts
Ser2a324ab3e D
pr26ate stat2c =21a3 3o1: ser2a3%ers2o1UI 9 HL*
;Id
;!e1erated%a3ue(strate:89!e1erat2o1T8pe.IENTITY)
pr26ate I1te:er 2d*
pr26ate Str21: 1ame*
b2-d2rect2o1a3 ma18-to-o1e assoc2at2o1 to Cou1tr8
;$a18ToO1e
pr26ate Cou1tr8 cou1tr8*
pub32c C2t8() D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
44/255
pub32c I1te:er :etId() D retur1 th2s.2d*
pub32c 6o2d setId(I1te:er 2d) D th2s.2d 9 2d*
pub32c Str21: :etName() D retur1 th2s.1ame*
pub32c 6o2d setName(Str21: 1ame) D th2s.1ame 9 1ame*
pub32c Cou1tr8 :etCou1tr8() D retur1 th2s.cou1tr8*
pub32c 6o2d setCou1tr8(Cou1tr8 cou1tr8) D th2s.cou1tr8 9 cou1tr8*
The generate# entities are normal classes plain ol# Java obects or 4
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
45/255
you never get the same value twice. The value by which the seuence is incremente# after a #raw
#efaults to & but it can be set when the seuence is create# using INCRE$ENT BY.
Chile it is most natural to let the seuence increment by & it actually ma$es sense to use a higher
value. !magine a seuence incrementing by 3+. Then you essentially get not one but 3+ eclusive
values with one single #raw. Thus the program #rawing the values #oes not have to ma$e 3+ trips to
the #atabase but only one. This increases performance.
GlassFish #efaults to an increment fo 3+ but what if your #atabase has alrea#y been create# with
an increment of & 7or any other value but 3+9D ou can"t simply change the increment because
eisting #atabase clients #epen# on the current value. Thus you have to tell J4A what your
increment value is.
2ere is the C2t8entity once again but this time we use an .pers2ste1ce.P*
;E1t2t8
pub32c c3ass C2t8 e>te1ds com.ma1ess21:[email protected] 2mp3eme1ts
Ser2a324ab3e D
pr26ate stat2c =21a3 3o1: ser2a3%ers2o1UI 9 HL*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
46/255
;Id
;Seue1ce!e1erator(1ame9?CITY+I+!ENERATOR?# seue1ceName9?CITY+I+SE?)
;!e1erated%a3ue(strate:89!e1erat2o1T8pe.SEUENCE#
:e1erator9?CITY+I+!ENERATOR?)
pr26ate Lo1: 2d*
pr26ate Str21: 1ame*
b2-d2rect2o1a3 ma18-to-o1e assoc2at2o1 to Cou1tr8
;$a18ToO1e
;
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
47/255
pub32c 6o2d setName(Str21: 1ame) D th2s.1ame 9 1ame*
pub32c Cou1tr8 :etCou1tr8() D retur1 th2s.cou1tr8*
pub32c 6o2d setCou1tr8(Cou1tr8 cou1tr8) D th2s.cou1tr8 9 cou1tr8*
Ce can specify the allocation sie of the un#erlying seuence 7here CITY+I+SE9 by specifying the
attribute a33ocat2o1S24eto the ;Seue1ce!e1eratorannotation for instance li$e this-
;Id
;Seue1ce!e1erator(1ame9?CITY+I+!ENERATOR?# seue1ceName9?CITY+I+SE?#
a33ocat2o1S24e9H)
;!e1erated%a3ue(strate:89!e1erat2o1T8pe.SEUENCE#
:e1erator9?CITY+I+!ENERATOR?)
pr26ate Lo1: 2d*
The problem is that we woul# have to change the generate# entity but this is something that we
#on"t want to #o. !#eally the co#e generator woul# have create# the attribute in the first place but
this #i# not happen. Fortunately there is an alternative to e#iting generate# co#e.
=i$e everywhere in the Java Enterprise E#ition annotations are only one way to specify things. The
other way are the goo# ol# K(= configuration files an# when a Java EE server sees both the K(=
configuaration wins. This is goo# because you can overri#e annotate# specifications at runtime
without having to recompile the application. That way an a#ministrator can ma$e configuration
changes an# #oes not rely on a #eveloper.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
48/255
!n our case we have to create a file e@b$odu3e$ETA-IN0ec32pse321k-orm.>m3 in the EJB
proect. Ce #o that by calling >ew / K(= from the contet menu of the #irectory $ETA-IN0in the
4roect Eplorer.
Fe1t2t8-mapp21:s 6ers2o19?H.?
>[email protected]>m31spers2ste1ceorm?
>m31s>s29?http555.5Q.or:JH/$LSchema-21sta1ce?
>[email protected]>m31spers2ste1ceorm
[email protected]>m31spers2ste1ceorm+H+.>sd?G
Fseue1ce-:e1erator
1ame9?COUNTRY+I+!ENERATOR?
seue1ce-1ame9?COUNTRY+I+SE?
212t2a3-6a3ue9?H?
a33ocat2o1-s24e9?H?
G
Fseue1ce-:e1erator
1ame9?CITY+I+!ENERATOR?
seue1ce-1ame9?CITY+I+SE?
212t2a3-6a3ue9?H?
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
49/255
a33ocat2o1-s24e9?H?
G
Fe1t2t8-mapp21:sG
Be careful though- Chenever we a## a new table 7or actually a new seuence9 we have to change
this K(= configuaration
This conclu#es our #iversion to
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
50/255
;Loca3Bea1
;State3ess
pub32c c3ass CookbookEao D
;,ers2ste1ceCo1te>t
E1t2t8$a1a:er em*
pub32c CookbookEao() D
pub32c 3o1: cou1tCou1tr2es() D
3o1: resu3t*
uer8 9 em.createuer8(?se3ect cou1t(co) =rom Cou1tr8 co?)*
resu3t 9 (Lo1:).:etS21:3eResu3t()*
retur1 resu3t*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
51/255
Ce use a fiel# variable of type Entity(anager attribute# with ;,ers2ste1ceCo1te>t an# we #on"t
initialie this variable. !t is automatically inecte# by the EJB container.
The metho# cou1tCou1tr2es()uses this entity manager to create a uery eecutes the uery
7that"s what happens in :etS21:3eResu3t()an# finally returns the result.
Ce coul# have written that much more compact as
retur1 (Lo1:)em.createuer8(?se3ect cou1t(co) =rom Cou1tr8
co?).:etS21:3eResu3t()*
but the longer variant has the a#vantage that it is easier to un#erstan# self#ocumenting an# you
can set a brea$point in the #ebugger.
-sing the EA# and looking "or an error
>ow that we have an EA
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
52/255
2mport com.ma1ess21:er.cookbook.eao.CookbookEao*
;Loca3Bea1
;State3ess
;"ebSer62ce
pub32c c3ass CookbookBea1 2mp3eme1ts CookbookI1ter=ace D
;E
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
53/255
Ce have a##e# a fiel# variable eao have attibute# it an# epect an EA< instance to be inecte#
upon each call of the toplevel metho# cou1tr8Cou1t(). This actually happens but then we get an
error.
Chen we call cou1tr8Cou1t()from the GlassFish Ceb ervice tester instea# of the epecte#
result * we get the following error-
Ser62ce 216ocat2o1 thre5 a1 e>cept2o1 52th messa:e 1u33*
Re=er to the ser6er 3o: =or more deta23s
E>cept2o1s deta23s @a6a.3a1:.re=3ect.I16ocat2o1Tar:etE>cept2o1
@a6a>.ser63et.Ser63etE>cept2o1 @a6a.3a1:.re=3ect.I16ocat2o1Tar:etE>cept2o1 at
...
... ma18 321es om2tted
...
or:.apache.derb8.c32e1t.am.S3E>cept2o1 Tab3e%2e5 7COUNTRY7 does 1ot e>2st.
at or:.apache.derb8.c32e1t.am.Stateme1t.comp3eteS3ca(U1k1o51 Source) at
...
... ma18 more 321e om2tted
...
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
54/255
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
55/255
Funny huhD @hronologically the net eception is
U1e>pected e>cept2o1 5h23e creat21: resource =or poo3 erb8,oo3.
E>cept2o1 @a6a>.resource.sp2.ResourceA33ocat2o1E>cept2o1 Co11ect2o1 cou3d
1ot be a33ocated because
@a6a.1et.Co11ectE>cept2o1 Error co11ect21: to ser6er 3oca3host o1 port H'J
52th messa:e Co11ect2o1 re=used.
an# then
0a23ed to obta21create co11ect2o1 =rom co11ect2o1 poo3 erb8,oo3 .
Reaso1 com.su1.appser6.co11ectors.21ter1a3.ap2.,oo321:E>cept2o1
Co11ect2o1 cou3d 1ot be a33ocated because
@a6a.1et.Co11ectE>cept2o1 Error co11ect21: to ser6er 3oca3host o1 port H'J
52th messa:e Co11ect2o1 re=used.
This is followe# by more consecutive faults. Chat"s happening hereD Ce use o won#er that GlassFish coul#n"t fin# a table
@T8 even when we really use# ?erby. GlassFish was never tol# about a cookbookdb all it
$new was the sample #atabase.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
56/255
Speci"ying the database1 testing1 S2% log
Chatever the #atabase it is clear that GlassFish has to be tol# about it. =et"s #o that. Ce nee# to #o
two things-
First we have to create a reference in GlassFish that points to the #atabase. econ# we have to
change the application in a way that it tells GlassFish which one of possibly several #atabases
#efine# in GlassFish we want to use. =et"s begin with creating the reference.
uch a reference consists of two parts a J?B@ connection pool an# a J>?! name #efinition refering
to the pool. This J>?! name finally is what we will use in the application to point to the #atabase.
reating connection pools and '! resources in the Adinistration onsole
Ce open the a#ministration console an# go to 8esources / J?B@ / @onnection 4ools. There we see
a list of the currently #efine# connection pools.
tep & of the >ew J?B@ @onnection 4ool wiar# reuires us to use a 8esource Type. The help
page of the wiar# tells us that
Available resource types are javax.sql.XADataSource(global transactions),
java.sql.ConnectionPoolDataSource(local transactions, possible performance
improvements), javax.sql.DataSource(local transactions only), and java.sql.Driver
. For the purpose of our tutorial @a6a>.s3.ataSourceis .s3./AataSource. They are a little more epensive consuming more memory but that"s
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
57/255
the price for the a##e# fleibility. There will be a separate post about multi#atabase scenarios
shortly.
2ere we enter a name for the new pool choose ?erby as #atabase ven#or an# go on to the net
screen. ?! name. Go to 8esources / J?B@ / J?B@ 8esources a## a new one
an# connect it to the new pool.
reating connection pools and '! resources using asadin
Ce can #o that in GlassFish"s A#ministration @onsole web application as we ust #i# an# we can
also #o it using the asa#min comman#line utility. Chatever you can #o in the A#ministration
@onsole you can #o in asa#min as well an# then suppose#ly some things more. 2ere is a session
in Cin#ows where ! have create# the same resources as in the web application.
CUsersA1dreasGasadm21 --port K --user adm21
create-@dbc-co11ect2o1-poo3
--datasourcec3ass1ame or:[email protected]
--rest8pe @a6a>.s3.ataSource
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
58/255
--propert8
portNumber9H'Jpass5ord9cookbookuser9cookbookuserser6erName93oca3hostdatab
aseName9cookbookdbco11ect2o1Attr2butes9*create9true Cookbook,oo3
Comma1d create-@dbc-co11ect2o1-poo3 e>ecuted success=u338.
Bac$slashes at line en# are not to be type# they mean the comman# continues on the net line. o
far we have a connection pool. >et we list connection pools an# loo$ if it"s there.
CUsersA1dreasGasadm21 --port K --user adm21 32st-@dbc-co11ect2o1-poo3s
++T2mer,oo3
erb8,oo3
Cookbook,oo3
up it is. =et"s try to ping it i.e. test it by ma$ing a connection.
CUsersA1dreasGasadm21 --port K --user adm21 p21:-co11ect2o1-poo3
Cookbook,oo3
Comma1d p21:-co11ect2o1-poo3 e>ecuted success=u338.
The connection wor$s. >ow we create the J?B@ resource #efinition.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
59/255
CUsersA1dreasGasadm21 --port K --user adm21 create-@dbc-resource
--co11ect2o1poo32d Cookbook,oo3 @dbccookbookdb
Comma1d create-@dbc-resource e>ecuted success=u338.
=ist J?B@ resources an# loo$ if it wor$e#.
CUsersA1dreasGasadm21 --port K --user adm21 32st-@dbc-resources
@dbc++T2mer,oo3
@dbc++de=au3t
@dbccookbookdb
!n or#er to ma$e this wor$ ! ha# to put two #irectories on the path 7environment variable ,athin
Cin#ows 59- the #irectory that contains @a6a.e>e7C,ro:ram 023es (>)
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
60/255
an# then ! woul# have been able to type the subcomman#s li$e create#bcconnectionpool #irectly
one after the other. !n the en# ! woul# have left asa#min by typing eit
Re"erencing the '! resource "ro the application
At this point GlassFish $nows about a #atabase that can be reference# as #bc/coo$boo$#b but we
still #on"t reference it from the application. =et"s #o that now-
!n the 4roect Eplorer we locate the file persistence.ml open it go to the @onnection tab a## the
J>?! name as JTA #ata source an# save the file. >ow try to call cou1tr8Cou1t()from the
GlassFish Ceb ervice tester again an# this time you"ll get the epecte# result *.
!f you want to see the #atabase statements in Eclipse"s @onsole view go to the =ogging tab set the
=ogging level to Fine an# try the call again. !f you #on"t see the server log then you have to switch
between consoles. Fin# the button that !"ve mar$e# re# on the right si#e of the @onsole view an#
use it to switch to the server log. >ow you shoul# see the statement.
0INE SELECT COUNT(I) 0RO$ COUNTRY
!f you loo$ at persistence.ml in the ource tab you see the following K(= co#e 7some namespace
#efinitions omitte# #on"t copy/paste this9-
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
61/255
FM>m3 6ers2o19?H.? e1cod21:9?UT0-?MG
Fpers2ste1ce 6ers2o19?H.? ...G
Fpers2ste1ce-u12t 1ame9?cookbookE
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
62/255
but when we try to a## this metho# to the 8emote !nterface we see that Eclipse flags an error.
Cou1tr8is not #efine# in the client proect. Chat nowD
Ce coul# create the entities in coo$boo$EJB@lient instea# of the EJB proect coo$boo$EJB but that
won"t wor$. The contet menu of the client proect #oes not give us the option to create entities from
tables. Another option woul# be to move the generate# entities from the EJB proect to the client
proect. This woul# wor$ but it is te#ious an# it woul# have to be repeate# every time we nee# to
generate anew.
eemingly the tool #oesn"t want to #o it our way an# whenever something li$e that happens it"s a
goo# i#ea to thin$ twice if what we want to achieve is really what we nee# to #o.
!n#ee# that"s not the case here. Entities #irectly reflect the inner structure of the #atabase an# that
is something that we shoul# avoi# to epose. Chen we sen# entities over the interface then we
actually sen# them over the networ$. They become part of the contract if they change because the
#atabase has change# clients have to be change# as well. >ot a goo# i#ea. Ce will want to insert
an abstraction layer comprising all #atatypes use# as parameters to business interface metho#s.
Ce call such obects ?ata Transfer
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
63/255
with Cou1tr8umphol#ing the information about a country. Alternatively we coul# write it as 7)9
pub32c Cou1tr8ump dumpCou1tr2es()*
or even 7*9
pub32c umpRespo1se dumpCou1tr2es()*
where umpRespo1sewoul# hol# an array of Cou1tr8ump. Java serialies all three versions to
more or less
FM>m3 6ers2o19?H.? e1cod21:9?UT0-?MG
FSE16e3ope >m31sS9?httpschemas.>m3soap.or:soape16e3ope?G
FSBod8G
F1sJdumpRespo1se
>m31s1sJ9?httpser62ce.cookbook.ma1ess21:er.com?G
Fretur1G
Fc2t2esG"2e1Fc2t2esG
Fc2t2esGL214Fc2t2esG
Fc2t2esG!ra4Fc2t2esG
Fc2t2esGSa34bur:Fc2t2esG
F1ameGAustr2aF1ameG
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
64/255
Fretur1G
Fretur1G
Fc2t2esGRomaFc2t2esG
Fc2t2esGBo3o:1aFc2t2esG
Fc2t2esG02re14eFc2t2esG
Fc2t2esG%e1e42aFc2t2esG
F1ameGIta38F1ameG
Fretur1G
Fretur1G
Fc2t2esGNe5 YorkFc2t2esG
Fc2t2esGLos A1:e3esFc2t2esG
Fc2t2esGAt3a1taFc2t2esG
Fc2t2esG"ash21:to1Fc2t2esG
F1ameGUSAF1ameG
Fretur1G
F1sJdumpRespo1seG
FSBod8G
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
65/255
FSE16e3opeG
or a veriant thereof with slightly #ifferent element names. (icrosoft .>ET woul# #eserialie all three
into something li$e R*. %ariant 7&9 relies on
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
66/255
!n many cases especially in the initial program version there will be a close onetoone
correspon#ence between entities an# ?T
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
67/255
packa:e com.ma1ess21:er.cookbook.dto*
2mport @a6a.ut23.L2st*
pub32c c3ass Cou1tr8ump D
pr26ate Str21: 1ame*
pr26ate L2stFStr21:G c2t2es*
pub32c Str21: :etName() D retur1 1ame*
pub32c 6o2d setName(Str21: 1ame) D th2s.1ame 9 1ame*
pub32c L2stFStr21:G :etC2t2es() D retur1 c2t2es*
pub32c 6o2d setC2t2es(L2stFStr21:G c2t2es) D th2s.c2t2es 9 c2t2es*
in the interface
packa:e com.ma1ess21:er.cookbook.ser62ce*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
68/255
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]*
2mport com.ma1ess21:er.cookbook.dto.Cou1tr8ump*
;Remote
pub32c 21ter=ace CookbookI1ter=ace D
pub32c 3o1: cou1tr8Cou1t()*
pub32c L2stFCou1tr8umpG dumpCou1tr2es()*
in the service bean
packa:e com.ma1ess21:er.cookbook.ser62ce*
2mport @a6a.ut23.Arra8L2st*
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]@b.Loca3Bea1*
2mport @a6a>[email protected]*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
69/255
2mport @a6a>.@5s."ebSer62ce*
2mport com.ma1ess21:er.cookbook.dto.Cou1tr8ump*
2mport com.ma1ess21:er.cookbook.eao.CookbookEao*
2mport com.ma1ess21:er.cookbook.e1t2t8.Cou1tr8*
2mport com.ma1ess21:er.cookbook.ut23.Co16ers2o1*
;Loca3Bea1
;State3ess
;"ebSer62ce
pub32c c3ass CookbookBea1 2mp3eme1ts CookbookI1ter=ace D
;E
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
70/255
pub32c 3o1: cou1tr8Cou1t() D
retur1 eao.cou1tCou1tr2es()*
;O6err2de
pub32c L2stFCou1tr8umpG dumpCou1tr2es() D
L2stFCou1tr8umpG resu3t 9 1e5 Arra8L2stFCou1tr8umpG()*
L2stFCou1tr8G a33Cou1tr2es 9 eao.a33Cou1tr2es()*
=or (Cou1tr8 c a33Cou1tr2es) D
Cou1tr8ump c2 9 co16.=romE1t2t8(c)*
resu3t.add(c2)*
retur1 resu3t*
in the [email protected]*
2mport @a6a>[email protected]*
2mport @a6a>.pers2ste1ce.E1t2t8$a1a:er*
2mport @a6a>.pers2ste1ce.,ers2ste1ceCo1te>t*
2mport @a6a>.pers2ste1ce.uer8*
2mport com.ma1ess21:er.cookbook.e1t2t8.Cou1tr8*
;Loca3Bea1
;State3ess
pub32c c3ass CookbookEao D
;,ers2ste1ceCo1te>t
E1t2t8$a1a:er em*
pub32c CookbookEao() D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
72/255
pub32c 3o1: cou1tCou1tr2es() D
3o1: resu3t*
uer8 9 em.createuer8(?se3ect cou1t(co) =rom Cou1tr8 co?)*
resu3t 9 (Lo1:).:etS21:3eResu3t()*
retur1 resu3t*
;Suppress"ar121:s(?u1checked?)
pub32c L2stFCou1tr8G a33Cou1tr2es() D
L2stFCou1tr8G resu3t*
uer8 9 em.createuer8(?se3ect co =rom Cou1tr8 co?)*
resu3t 9 (L2stFCou1tr8G) .:etResu3tL2st()*
retur1 resu3t*
an# finally in the converter
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
73/255
packa:e com.ma1ess21:er.cookbook.ut23*
2mport @a6a.ut23.Arra8L2st*
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]@b.State3ess*
2mport com.ma1ess21:er.cookbook.dto.Cou1tr8ump*
2mport com.ma1ess21:er.cookbook.eao.CookbookEao*
2mport com.ma1ess21:er.cookbook.e1t2t8.C2t8*
2mport com.ma1ess21:er.cookbook.e1t2t8.Cou1tr8*
;State3ess
pub32c c3ass Co16ers2o1 D
;E
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
74/255
pub32c Cou1tr8ump =romE1t2t8(Cou1tr8 e) D
Cou1tr8ump resu3t 9 1e5 Cou1tr8ump()*
resu3t.setName(e.:etName())*
L2stFStr21:G c2t2es 9 1e5 Arra8L2stFStr21:G()*
=or (C2t8 c2t8 e.:etC2t2es()) D
c2t2es.add(c2t8.:etName())*
resu3t.setC2t2es(c2t2es)*
retur1 resu3t*
After such maor changes involving new classes you may nee# to restart the server. >ormally
changes are automatically #eploye# but if too much structure is change# then a server restart can"t
be avoi#e#. This is such a point. Just remember to actually stop/start the server because restarting
has a bug right now.
-pdating de"inition in soap-$ and testing
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
75/255
Ce can test dumpCou1tr2es()in the GlassFish web service tester
7Appplications / proectEA8 / (o#ules an# @omponents / %iew En#point / Tester9 or we can #o it in
soap1!. !n or#er to #o the latter we have to ma$e it up#ate its #efinition. Ce #o that from the contet
menu of @oo$boo$Bean4ortBin#ing with 1p#ate ?efinition.
Chen we finally ma$e the call we see the epecte# result-
FSE16e3ope >m31sS9?httpschemas.>m3soap.or:soape16e3ope?G
FSBod8G
F1sJdumpRespo1se >m31s1sJ9?httpser62ce.cookbook.ma1ess21:er.com?G
Fretur1G
Fc2t2esGL214Fc2t2esG
Fc2t2esG!ra4Fc2t2esG
Fc2t2esG"2e1Fc2t2esG
Fc2t2esGSa34bur:Fc2t2esG
F1ameGAustr2aF1ameG
Fretur1G
Fretur1G
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
76/255
Fc2t2esG%e1e42aFc2t2esG
Fc2t2esGRomaFc2t2esG
Fc2t2esGBo3o:1aFc2t2esG
Fc2t2esG02re14eFc2t2esG
F1ameGIta38F1ameG
Fretur1G
Fretur1G
Fc2t2esGLos A1:e3esFc2t2esG
Fc2t2esG"ash21:to1Fc2t2esG
Fc2t2esGNe5 YorkFc2t2esG
Fc2t2esGAt3a1taFc2t2esG
F1ameGUSAF1ameG
Fretur1G
F1sJdumpRespo1seG
FSBod8G
FSE16e3opeG
Ce have #one nothing to maintain a particular sort or#er thus the or#er may vary from call to call.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
77/255
Accessing E!s "ro a servlet
>ot always #oes it suffice to access Enterprise Java Beans via ew / ?ynamic Ceb 4roect.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
78/255
From the contet menu of the new proect we select Buil# 4ath / @onfigure Buil# 4ath an# a## the
EJB proect to the buil# path. >ow we have access to all types in the EJB proect as well as the
client proect.
The ?ynamic Ceb 4roect has a source fol#er src an# from its contet menu we choose >ew /
4ac$age. Ce see the servlet as a $in# of service thus we use again the pac$age name
com.manessinger.coo$boo$.service.
reating a servlet
From the contet menu of the pac$age we choose >ew / Ceb ervlet 7Java EE 69.
Ce call the servlet class Cou1tr8L2stan# accept the #efaults. The result is this class 7comments
omitte#9-
packa:e com.ma1ess21:er.cookbook.ser62ce*
2mport @a6a.2o.IOE>cept2o1*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
79/255
2mport @a6a.2o.,r21t"r2ter*
2mport @a6a>.ser63et.Ser63etE>cept2o1*
2mport @a6a>.ser63et.a11otat2o1."ebSer63et*
2mport @a6a>.ser63et.http.&ttpSer63et*
2mport @a6a>.ser63et.http.&ttpSer63etReuest*
2mport @a6a>.ser63et.http.&ttpSer63etRespo1se*
;"ebSer63et(1ame 9 ?Cou1tr8L2st?# ur3,atter1s 9 D ?Cou1tr8L2st? )
pub32c c3ass Cou1tr8L2st e>te1ds &ttpSer63et D
pr26ate stat2c =21a3 3o1: ser2a3%ers2o1UI 9 HL*
pub32c Cou1tr8L2st() D super()*
protected 6o2d do!et(&ttpSer63etReuest reuest# &ttpSer63etRespo1se
respo1se)
thro5s Ser63etE>cept2o1# IOE>cept2o1 D
processReuest(reuest# respo1se)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
80/255
protected 6o2d do,ost(&ttpSer63etReuest reuest# &ttpSer63etRespo1se
respo1se)
thro5s Ser63etE>cept2o1# IOE>cept2o1 D
processReuest(reuest# respo1se)*
protected 6o2d processReuest(&ttpSer63etReuest reuest#
&ttpSer63etRespo1se respo1se) thro5s Ser63etE>cept2o1# IOE>cept2o1
D
respo1se.setCo1te1tT8pe(?te>thtm3*charset9UT0-?)*
,r21t"r2ter out 9 respo1se.:et"r2ter()*
tr8 D
out.pr21t31(?Fhtm3G?)*
out.pr21t31(?FheadG?)*
out.pr21t31(?Ft2t3eGSer63et Cou1tr8L2stFt2t3eG?)*
out.pr21t31(?FheadG?)*
out.pr21t31(?Fbod8G?)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
81/255
out.pr21t31(?FhHGSer63et Cou1tr8L2st at ?
V reuest.:etCo1te>t,ath() V ?FhHG?)*
out.pr21t31(?Fbod8G?)*
out.pr21t31(?Fhtm3G?)*
=21a338 D
out.c3ose()*
;O6err2de
pub32c Str21: :etSer63etI1=o() D retur1 ?Short descr2pt2o1?*
ou may nee# to stop/start the server again an# then you can alrea#y call the servlet un#er the
following 18= 7portnumber may be #ifferent chec$ with the server9-
http3oca3hostKcookbookSer63etsCou1tr8L2st
Accessing the E!
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
82/255
>ow we change the servlet co#e an# a## an EJB as uninitialie# fiel# annotate# with UEJB. Ce
call the dumpCou1tr2es()metho# an# print the result into an 2T(= #efinition list insi#e of a ?!%
element. 2ere is the co#e-
packa:e com.ma1ess21:er.cookbook.ser62ce*
2mport @a6a.2o.IOE>cept2o1*
2mport @a6a.2o.,r21t"r2ter*
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]>cept2o1*
2mport @a6a>.ser63et.a11otat2o1."ebSer63et*
2mport @a6a>.ser63et.http.&ttpSer63et*
2mport @a6a>.ser63et.http.&ttpSer63etReuest*
2mport @a6a>.ser63et.http.&ttpSer63etRespo1se*
2mport com.ma1ess21:er.cookbook.dto.Cou1tr8ump*
;"ebSer63et(1ame 9 ?Cou1tr8L2st?# ur3,atter1s 9 D ?Cou1tr8L2st? )
pub32c c3ass Cou1tr8L2st e>te1ds &ttpSer63et D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
83/255
pr26ate stat2c =21a3 3o1: ser2a3%ers2o1UI 9 HL*
;Ecept2o1# IOE>cept2o1 D
processReuest(reuest# respo1se)*
protected 6o2d do,ost(&ttpSer63etReuest reuest# &ttpSer63etRespo1se
respo1se)
thro5s Ser63etE>cept2o1# IOE>cept2o1 D
processReuest(reuest# respo1se)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
84/255
protected 6o2d processReuest(&ttpSer63etReuest reuest#
&ttpSer63etRespo1se respo1se) thro5s Ser63etE>cept2o1# IOE>cept2o1
D
respo1se.setCo1te1tT8pe(?te>thtm3*charset9UT0-?)*
,r21t"r2ter out 9 respo1se.:et"r2ter()*
tr8 D
out.pr21t31(?Fhtm3G?)*
out.pr21t31(?FheadG?)*
out.pr21t31(?Ft2t3eGCou1tr8 32stFt2t3eG?)*
out.pr21t31(?FheadG?)*
out.pr21t31(?Fbod8G?)*
out.pr21t31(?FhHGCou1tr8 32stFhHG?)*
L2stFCou1tr8umpG cou1tr2es 9 cbBea1.dumpCou1tr2es()*
2= (cou1tr2es.s24e() G ) D
out.pr21t31(?Fd26 c3ass9?cookbook-cou1tr8-32st?G?)*
out.pr21t31(?Fd3G?)*
=or (Cou1tr8ump co cou1tr2es) D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
85/255
out.pr21t31(?Fd2G?Vco.:etName()V?Fd2G?)*
out.pr21t31(?FddG?)*
L2stFStr21:G c2t2es 9 co.:etC2t2es()*
2= (c2t2es.s24e() G ) D
out.pr21t31(?Fu3G?)*
=or (Str21: c2 c2t2es) D
out.pr21t31(?F32G?Vc2V?F32G?)*
out.pr21t31(?Fu3G?)*
out.pr21t31(?FddG?)*
out.pr21t31(?Fd3G?)*
out.pr21t31(?Fd26G?)*
out.pr21t31(?Fbod8G?)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
86/255
out.pr21t31(?Fhtm3G?)*
=21a338 D
out.c3ose()*
;O6err2de
pub32c Str21: :etSer63etI1=o() D
retur1 ?2sp3a8s a 32st o= cou1tr2es a1d some o= the2r c2t2es?*
This is it. Ce get a list.
-nit tests
1nit tests are a means to ma$e sure that by a##ing new co#e or mo#ifying eisting one you #on"t
ina#vertently brea$ what alrea#y wor$s. 1nit tests are ust small test programs that verify the
contracts of the units of co#e that they test. 4rogrammers always have #one that it"s ust that
Etreme 4rogrammingma#e their use man#atory an# that Lent Bec$ an# Erich Gamma #evise# a
clever but simple framewor$ calle# J1nit.
1nit tests can be eecute# from within Eclipse 7or any of the other popular Java !?Es9 they can be
run via Ant an# they are run by socallen continuous integration servers li$e 2u#son. !n many
http://en.wikipedia.org/wiki/Extreme_Programminghttp://hudson-ci.org/http://en.wikipedia.org/wiki/Extreme_Programminghttp://hudson-ci.org/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
87/255
organiations an# proects a successful run of the unit test suite is even precon#ition for a chec$in
into the version control system.
!n times of J)EE unit testing EJBs was notoriously har# mostly because the beans were not
4
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
88/255
use Java at all. A language that is not as easy to #ecompile woul# suit you better. !n this contet !
assume that this is a nonissue.
Project setup
Ce begin setting up the test proect an or#inary Java proect calle# coo$boo$J1nit!nerver.
!n or#er to have access to all beans in the server epose# via client libraries or not we #on"t put the
client proect on the buil# path but the EJB proect coo$boo$EJB instea#. Ce nee# to a## Junit
libraries to the proect an# we #o this via =ibraries / A## =ibrary / J1nit / J1nit '. imilarly we nee#
the client library for access to GlassFish. >ote though that you #on"t get that via =ibraries / A##
=ibrary / erver 8untime / GlassFish v* JEE 6. The library we nee# is calle# gfclient.ar an# it is
locate# in the GlassFish mo#ules #irectory. ?! loo$up i.e. by calling
the 3ookup()metho# of an I12t2a3Co1te>t but in this case we have to go a little further.
I12t2a3Co1te>tcomes with normal Java E an# it #oes not $now about JEE or GlassFish. Cehave to provi#e some hints when constructing the I12t2a3Co1te>t. These hints are given to the
constructor as a set of properties. Ce want one place where these properties are #efine# thus we
create a pac$age in the test proect calle# com.manessinger.unit. 2ere we create a class Ut23with
a static metho# ,ropert2es :etI12t,ropert2es().
http://download.java.net/glassfish/eclipse/http://download.java.net/glassfish/eclipse/http://download.java.net/glassfish/eclipse/http://download.java.net/glassfish/eclipse/ -
7/24/2019 An EclipseJavaEE6 PostgreSQL
89/255
packa:e com.ma1ess21:er.@u12t*
2mport @a6a.ut23.,ropert2es*
pub32c c3ass Ut23 D
pub32c stat2c ,ropert2es :etI12t,ropert2es() D
,ropert2es resu3t 9 1e5 ,ropert2es()*
"e 1eed to te33 the co1te>t 5here a1d ho5 to 3ook
resu3t.set,ropert8([email protected]:.=actor8.212t2a3?#
?com.su1.e1terpr2se.1am21:.Ser2a3I12tCo1te>t0actor8?)*
resu3t.set,ropert8([email protected]:.=actor8.ur3.pk:s?#
?com.su1.e1terpr2se.1am21:?)*
resu3t.set,ropert8([email protected]:.=actor8.state?#
?com.su1.corba.ee.2mp3.prese1tat2o1.rm2.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
90/255
Shou3d 1ot be 1ecessar8 =or 3oca3 test (de=au3t 6a3ues)# but
curre1t38 2s
resu3t.set,ropert8(?or:.om:.CORBA.ORBI12t2a3&ost?# ?3oca3host?)*
resu3t.set,ropert8(?or:.om:.CORBA.ORBI12t2a3,ort?# ?Q?)*
retur1 resu3t*
The first bloc$ of three properties causes J>?! to use GlassFishspecific libraries for the loo$up. The
secon# bloc$ with or:.om:.CORBA.ORBI12t2a3&ostan# or:.om:.CORBA.ORBI12t2a3,ortis
interesting though. The values specifie# shoul# be #efault values but fact is that they currently are
not.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
91/255
Cin#ows 7why shoul# it beD9 or if it was the result of me tin$ering with the installation but it #oes not
hurt to have a loo$.
Testing and a &otSeriali.ableE6ception
>o we can write a simple test class for our EJB. >ote that we always put our test classes into
pac$ages with the same names 7as pac$ages are namespaces essentially meaning they are in the
same pac$age9 as the classes un#er test. Thus we first create a pac$age
com.manessinger.coo$boo$.service in the test proect an# then we create the test class-
packa:e com.ma1ess21:er.cookbook.ser62ce*
2mport stat2c or:[email protected]*
2mport @a6a.ut23.L2st*
2mport @a6a>.1am21:.I12t2a3Co1te>t*
2mport or:[email protected]=ore*
2mport or:[email protected]*
2mport com.ma1ess21:er.cookbook.dto.Cou1tr8ump*
2mport com.ma1ess21:[email protected]*
pub32c c3ass TestCookbookBea1 D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
92/255
pr26ate CookbookI1ter=ace ser62ceBea1*
;Be=ore
pub32c 6o2d setUp() thro5s E>cept2o1 D
ser62ceBea1 9
(CookbookI1ter=ace) 1e5 I12t2a3Co1te>t(Ut23.:etI12t,ropert2es())
.3ookup(?@a6a:3oba3cookbookEARcookbookE
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
93/255
pub32c 6o2d dumpTest() D
L2stFCou1tr8umpG cou1tr2es 9 ser62ceBea1.dumpCou1tr2es()*
assertEua3s(Q# cou1tr2es.s24e())*
=or (Cou1tr8ump co cou1tr2es) D
assertEua3s(K# co.:etC2t2es().s24e())*
Ce run a unit test by rightclic$ing in the file an# calling 8un As / J1nit Test from the contet menu.
This pops up the J1nit view but when you are in the Java EE perspective it may still be #own where
the erver view an# @onsole view are. Just ta$e the tab an# #rag it onto the 4roect Eplorer tab on
the left si#e or the Eclipse win#ow. That"s where it is in the normal Java perspective an# this is amuch better place.
Chen you run the test li$e that you will see that cou1tr8Cou1tTest()succee#s but dumpTest()
fails with
@a6a>[email protected]
@a6a.rm2.$arsha3E>cept2o1 CORBA BA+,ARA$ HQQKKQKJ $a8be*
1ested e>cept2o1 2s
@a6a.2o.NotSer2a324ab3eE>cept2o1
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
94/255
----------BE!IN ser6er-s2de stack trace----------
or:.om:.CORBA.BA+,ARA$ 6mc2d
O$! m21or code comp3eted $a8be
at com.su1.corba.ee.2mp3.3o::21:.O$!S8stemE>cept2o1.1otSer2a324ab3e
an# so on an# so on. Chat"s wrongD
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
95/255
pr26ate stat2c =21a3 3o1: ser2a3%ers2o1UI 9 HL*
pr26ate Str21: 1ame*
pr26ate L2stFStr21:G c2t2es*
pub32c Str21: :etName() D retur1 1ame*
pub32c 6o2d setName(Str21: 1ame) D th2s.1ame 9 1ame*
pub32c L2stFStr21:G :etC2t2es() D retur1 c2t2es*
pub32c 6o2d setC2t2es(L2stFStr21:G c2t2es) D th2s.c2t2es 9 c2t2es*
Ce #i#n"t get the error before because so far we ha# calle# dumpCou1tr2es()only via
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
96/255
Chen we loo$ bac$ at the test class we see an annotation ;Be=oreon the
metho# setup(). This is a J1nit ' annotation an# it means that the setup metho# is calle# before
each test metho#. There is another annotation ;Be=oreC3ass an# when we use that on a static
metho# it is calle# before the first test metho# an# finally there is another pair of annotations
;A=teran# ;A=terC3ass. They are obviously calle# after each metho# respectively after the last
test metho#.
!f we want to test the EA< 7which is the only other bean at the moment anyway9 we nee# it to
implement a 8emote !nterface. Ce #on"t want to have this interface in the client proect instea# we
put it into the EJB proect into the pac$age com.manessinger.coo$boo$.eao where the EA< itself is.
Ce #o that by using 8efactor / Etract !nterface from either the contet menu of @oo$boo$Eao.ava
in the 4roect Eplorer or from the contet menu of the class name within the file.
Etracting the interface is not enough though. Ce nee# to ma$e it a 8emote !nterface by a##ing the
;Remoteannotation-
packa:e com.ma1ess21:er.cookbook.eao*
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]*
2mport com.ma1ess21:er.cookbook.e1t2t8.Cou1tr8*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
97/255
;Remote
pub32c 21ter=ace CookbookEaoI1ter=ace D
pub32c 3o1: cou1tCou1tr2es()*
pub32c L2stFCou1tr8G a33Cou1tr2es()*
Chen we etracte# the interface the EA< has automatically been change# to implement it-
packa:e com.ma1ess21:er.cookbook.eao*
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]*
2mport @a6a>[email protected]*
2mport @a6a>.pers2ste1ce.E1t2t8$a1a:er*
2mport @a6a>.pers2ste1ce.,ers2ste1ceCo1te>t*
2mport @a6a>.pers2ste1ce.uer8*
2mport com.ma1ess21:er.cookbook.e1t2t8.Cou1tr8*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
98/255
;Loca3Bea1
;State3ess
pub32c c3ass CookbookEao 2mp3eme1ts CookbookEaoI1ter=ace D
;,ers2ste1ceCo1te>t
E1t2t8$a1a:er em*
pub32c CookbookEao() D
pub32c 3o1: cou1tCou1tr2es() D
3o1: resu3t*
uer8 9 em.createuer8(?se3ect cou1t(co) =rom Cou1tr8 co?)*
resu3t 9 (Lo1:).:etS21:3eResu3t()*
retur1 resu3t*
;Suppress"ar121:s(?u1checked?)
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
99/255
pub32c L2stFCou1tr8G a33Cou1tr2es() D
L2stFCou1tr8G resu3t*
uer8 9 em.createuer8(?se3ect co =rom Cou1tr8 co?)*
resu3t 9 (L2stFCou1tr8G) .:etResu3tL2st()*
retur1 resu3t*
>ow we can #o ust the same as for the service bean an# create a test class.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
100/255
pub32c c3ass TestCookbookEao D
pr26ate CookbookEaoI1ter=ace eao*
;Be=ore
pub32c 6o2d setUp() thro5s E>cept2o1 D
eao 9 (CookbookEaoI1ter=ace) 1e5
I12t2a3Co1te>t(Ut23.:etI12t,ropert2es())
.3ookup(?@a6a:3oba3cookbookEARcookbookE
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
101/255
Testsuite
>ow we have one test class per class teste# both in the test proect but in the same pac$ages as
the classes that they test. Ce can run each of them separately with 8un As / J1nit Test but we also
want the option to run the whole suite of tests. That"s what a J1nit test suite is for. 2ere is another
class that can be 8un As / J1nit Test an# this class will run all the in#ivi#ual test classes-
packa:e com.ma1ess21:er.cookbook*
2mport or:[email protected]"2th*
2mport or:[email protected]*
;Ru1"2th(Su2te.c3ass)
;Su2te.Su2teC3asses(D
com.ma1ess21:er.cookbook.ser62ce.TestCookbookBea1.c3ass#
com.ma1ess21:er.cookbook.eao.TestCookbookEao.c3ass#
)
pub32c c3ass A33Tests D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
102/255
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
103/255
Ce wor$ with J4A for #atabase access. J4A nee#s a file (ETA!>F/persistence.ml in its class path.
Ce can simply copy coo$boo$EJB/eb(o#ule/(ETA!>F an# paste it to
[email protected]>m31spers2ste1ce?
>m31s>s29?http555.5Q.or:JH/$LSchema-21sta1ce?
>[email protected]>m31spers2ste1ce
[email protected]>m31spers2ste1cepers2ste1ce+H+.>sd?G
Fpers2ste1ce-u12t [email protected]?
6a3ue9?or:[email protected]? G
Fpropert8 1ame9?@a6a>[email protected]?
6a3ue9?@dbcderb83oca3hostH'Jcookbookdb*create9true? G
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
104/255
Fpropert8 1ame9?@a6a>[email protected]?
6a3ue9?cookbookuser? G
Fpropert8 1ame9?@a6a>[email protected]?
6a3ue9?cookbook? G
Fpropert8 1ame9?ec32pse321k.3o::21:.3e6e3?
6a3ue9?0INE? G
Fpropert8 1ame9?ec32pse321k.tar:et-ser6er?
6a3ue9?com.ma1ess21:[email protected]/persistence.ml9 on the buil# path. Ce nee# to ma$e sure that our name is uniue because
otherwise we woul# #epen# on which persistence.ml is foun# first on the path.
Apart from changing the name of the persistence unit we have to a## some properties for specifying
the #atabase connection. !n the EJB proect 7an# also when testing inserver9 the connection ha#
been supplie# by the server in form of a J?B@ #ata source reference# by a J>?! name. >ow we
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
105/255
have no server thus we have to specify it here. This is also the way how you can use J4A without a
JEE environment.
!n this sample proect we use the same #atabase for testing as we use in the EJB proect. >ormally
you will not #o that. !nteractive tests ten# to change the #atabase but for testing you want a
#atabase with a well$nown set of recor#s. E but the last property is something new.
eclipselin$.targetserver refers to a class that we will have to implement. Chen you use J4A with the
libraries supplie# with GlassFish the #efault for this property woul# refer to a GlassFishinternal
class. That"s why we normally #on"t have to #efine this property. 2ere we have no GlassFish that"s
why we nee# a wor$aroun# an# again we put this wor$aroun# into a pac$age
com.manessinger.unit in the test proect.
packa:e com.ma1ess21:er.@u12t*
2mport @a6a>.tra1sact2o1.Tra1sact2o1$a1a:er*
pub32c c3ass te1ds
or:.ec32pse.pers2ste1ce.tra1sact2o1.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
106/255
pub32c cept2o1
D
retur1 (Tra1sact2o1$a1a:er) @1d2Lookup(.pers2ste1ce.E1t2t8$a1a:er*
2mport @a6a>.pers2ste1ce.,ers2ste1ce*
pub32c c3ass Ut23 D
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
107/255
pub32c stat2c E1t2t8$a1a:er :etE1t2t8$a1a:er() D
retur1 ,ers2ste1ce.createE1t2t8$a1a:er0actor8(?cookbookEow that we have prepare# the environment it"s easy to instrument the beans un#er test an# to
write the test classes. 8emember we have no running container that coul# inect EJBs or entity
managers thus we a## constructors. 2ere is the change# EA< with a constructor ta$ing an
E1t2t8$a1a:er-
packa:e com.ma1ess21:er.cookbook.eao*
2mport @a6a.ut23.L2st*
2mport @a6a>[email protected]*
2mport @a6a>[email protected]*
2mport @a6a>.pers2ste1ce.E1t2t8$a1a:er*
2mport @a6a>.pers2ste1ce.,ers2ste1ceCo1te>t*
2mport @a6a>.pers2ste1ce.uer8*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
108/255
2mport com.ma1ess21:er.cookbook.e1t2t8.Cou1tr8*
;Loca3Bea1
;State3ess
pub32c c3ass CookbookEao 2mp3eme1ts CookbookEaoI1ter=ace D
;,ers2ste1ceCo1te>t
E1t2t8$a1a:er em*
pub32c CookbookEao() D
pub32c CookbookEao(E1t2t8$a1a:er em) D th2s.em 9 em* =or u12t test
pub32c 3o1: cou1tCou1tr2es() D
3o1: resu3t*
uer8 9 em.createuer8(?se3ect cou1t(co) =rom Cou1tr8 co?)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
109/255
resu3t 9 (Lo1:).:etS21:3eResu3t()*
retur1 resu3t*
;Suppress"ar121:s(?u1checked?)
pub32c L2stFCou1tr8G a33Cou1tr2es() D
L2stFCou1tr8G resu3t*
uer8 9 em.createuer8(?se3ect co =rom Cou1tr8 co?)*
resu3t 9 (L2stFCou1tr8G) .:etResu3tL2st()*
retur1 resu3t*
This version of the EA< can be use# for both $in#s of testing.
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
110/255
2mport stat2c or:[email protected]*
2mport @a6a>.pers2ste1ce.E1t2t8$a1a:er*
2mport or:[email protected]=ore*
2mport or:[email protected]*
2mport com.ma1ess21:[email protected]*
pub32c c3ass TestCookbookEao D
pr26ate E1t2t8$a1a:er +em*
pr26ate CookbookEao eao*
;Be=ore
pub32c 6o2d setUp() thro5s E>cept2o1 D
+em 9 Ut23.:etE1t2t8$a1a:er()*
eao 9 1e5 CookbookEao(+em)*
-
7/24/2019 An EclipseJavaEE6 PostgreSQL
111/255
;Test
pub32c 6o2d cou1tr8Cou1tTest() D
3o1: 1 9 eao.cou1tCou1tr2es()*
assertEua3s(Q# 1)*
Again we start the test with 8un As / J1nit Test.
After the same pattern we a## another constructor to CookbookBea1
packa:e com.ma1ess