Schuchert - JPA Tutorial 1 - Getting Started
-
Upload
senthil-kumar -
Category
Documents
-
view
246 -
download
0
Transcript of Schuchert - JPA Tutorial 1 - Getting Started
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 1/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
Comments: please email: schuchert at ahoo dot com
Table of ContentsIntroduction
JPA Tutorial 1: Background
JPA Initial Setup
Eclipse Project Setup
Persistence Unit Configuration
Create Your First Entit
Add an Embedded Entit
Add an Entit ith a One to Man
Relationship
Make a Relationship Bi-Directional
Eercises
Entire Source Base
FAQ
<--Bac
InrodcionThi fi ia gie a i ih:
eig a eie i,ceaig i-e eiie ad
eiig he eiie a daabae.
Y' ie he cde ch ha he eie ceae he daabae chea baed ea-ifai (aai) i ei cae.
Gd c!
JPA Torial 1: BackgrondI hi fi ia e ae gig ef e baic ie, ee ad eieagai a daabae.
JPA a ih ei cae, hich ae deed a ch ig he aai @Ei cfiged i aXML fie (e' ca hi persistence meta information). Whe e acie he Entit Manager Factor ig hePersistence ca, he Entit Manager Factor fid ad cee he persistence meta information.
T ih a daabae ig JPA, e eed a Entit Manager. Befe e ca d ha, e eed ceae a EntitManager Factor.
T acie a Entit Manager Factor, e e he ca java.persistence.Persistence. I ead a fie caed eiece. i he META-INF diec. I he ceae he aed Entit Manager Factor, hich cee
JPA Torial 1 - Geing Sared EditEdit 3030 00 3333
You are not a member of this iki. Join no Dismiss
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 2/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
XML ( ).
C Entit Manager Entit Manager Factor :
O Entit Manager, .
Term Description
..P
T JPA. T ' EMF("N") "N". T eie persistence.ml META-INF.
EMF
A . E M - . T
. T E M F -
P U.
EM
A E M the . I , , , . I not- . T E M . I .
.A required . W
..P E M F, P META-INF .
P U
A P U ( JSE ) JNDI-
( /JEE ). A P U
() .
P MI
I . T XML . N XML .
JPA Initial SetupT J 5 (JDK 1.5) E 3.2 . T ' . W I , ' ... ' .
Noe: W . JPA. Y JEE . F , JB EJB3E , ' 150+ .
Download Ever thingF :1. D JSE 5 ( JDK 5.0 ( ))2. D E
N, :1. D H 3.3.1 GA2. D H A 3.4.0 GA3. D H E M 3.4.0.GA4. D HSQL D E 1.8.0.105. D SLF4J 1.5.8
6. D O EJB 3.1.1
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 3/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
. . .
Setup the JDK & Eclipse1. I JSE 5.2. E . F I C:/.
Etract Jar FilesE . I I C:/, I C://--3.4.0.GA
C://--3.4.0.GAC://--3.3.1.GAC://-1.9.0-3C://-3.1.1C://4-1.5.8
Eclipse Project Setup N .
Create Initial Project1. S .
2. W , . I C:\\JAE3. T I , .
3. C W
User LibrarW , . O , . T . W .1. P Windo:Pefeence2. N Jaa:Bild Pah:Ue Libaie3. C Ne4. E JPA_JSE OK
N . F , :1. S JPA_JSE ( , ' , UI
)2. C Add JAR...3. N 4. S 5. C Open6. R .
H ' ( ' C:/):C://--3.3.1.GA///-2.7.6. C://--3.3.1.GA///--3.1. C://--3.3.1.GA///4-1.6.1. C://--3.3.1.GA///-3.4.GA. C://--3.3.1.GA/3.
C:/-3.1.1//--5.0-2. C:/-3.1.1//4-1.2.12. C:/--3.4.0.GA/-. C:/-1.9.0-3///. C:/--3.4.0.GA/-. C:/--3.4.0.GA//--. C:/4-1.5.8/4--1.5.8. C:/4-1.5.8/4--1.5.8.
Create Java Project N J . W' :1. P File Ne:Pojec2. S Jaa Pojec Ne3. E : JpaToial1, I .
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 4/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
4. Make e "Ceae ne pojec in okpace" i eleced.5. Make e he JRE eleced i 1.5.. If a 1.5 JRE doe no ho in he li, o can add i hogh Windo-
>Pefeence->JAVA->Inalled JRE'.6. Selec "Ceae epaae oce and op folde"7. Click "finih"
Ceae flde ad ackage
1. Epand o pojec JpaToial12. Selec he c folde 3. Righ-click, elec ne:Folde
4. Ene he name META-INF5. Click Finih6. Selec he c folde again7. Righ-click, elec ne:Package8. Ene he name eni9. Click on Finih10. Selec he Toia1 pojec again11. Righ-click, elec ne:Soce Folde12. Ene he name e13. Click Finih14. Selec he e folde 15. Righ-click, elec ne:Package16. Ene he name eni
Add Reied LibaieWe no need o add o libaie. One ill be he e-defined liba e ceaed aboe. The econd ill be JUni 4..
1. Edi he pojec popeie. Selec o pojec (e.g. JpaToial1) and eihe pe al-eneo igh-click and elec popeie.
2. Selec Jaa Bild Pah3. Click on he Libaie ab4. Click on Add Liba5. Selec Ue Libaie and click Ne6. Selec JPA_JSE b clicking on he checkbo7. Click OK 8. Click on Add Liba again9. Click on JUni10. Click Ne
11. In he pll-don li, elec JUni 412. Click Finih13. Click OK
Sideba The JPA pecificaion a ha in a managed enionmen (ead a nning in he conaine), o do no need o li o eni clae in he peience.ml (hi i coming p). When o'e ing JPA in a JSE enionmen, hi i nogaaneed. In all of hee eample, e'e ing he hibenae implemenaion of he JEE Eni Manage. I poide hefncionali of aomaicall egieing all of o eniie iho o haing o eplicil li hem. Hoee, if ohappen o hae a pace in o cla pah, i appea o fail.
If o folloed he incion aboe, o'll hae he folloing dieco: C:/Wokpace/JpaAndEjb3/JpaToial1.
Unde ha dieco ill be a bin dieco hee o compiled cla file eide. Hibenae ill look in hi dieco andfind all clae ha ae eniie (denoed ih @Eni) and add hoe o o peien ni. In he fi eion of hioial, I ecommended he folloing name: C:/Wokpace/Jpa And Ejb3/Toial 1. When I an he die pogam,hibenae a nable o aomaicall find he bin dieco, I ame hi a becae of he pace in he name. Ichanged he name b emoing all of he pace and he poblem en aa.
Peiece Ui CfigaiWe no need o ceae he Peien Uni definiion. Ceae a file called peience.ml in he c/META-INF diecoih he folloing conen:
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 5/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
persistence.ml
<persistence>
<persistence-unit name="examplePersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<properties>
<propert name="hibernate.show_sql" value="false" />
<propert name="hibernate.format_sql" value="false" />
<propert name="hibernate.connection.driver_class"
value="org.hsqldb.jdbcDriver" />
<propert name="hibernate.connection.url"
value="jdbc:hsqldb:mem:mem:aname" />
<propert name="hibernate.connection.username" value="sa" />
<propert name="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect" />
<propert name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
The Steps1. Epand o pojec (JpaTutorial1)2. Selec he src/META-INF dieco
3. Righ click and elec ne:File4. Ene persistence.ml fo he name and pe Finish (Noe: all loecae. I on' make a diffeence on Windo
XP b i ill on Uni.)5. Cop he conen (aboe) ino he file and ae i.
Ve rif This Works1. Selec he test2. Righ-click on entit and elec ne:Class3. Ene PersonTest and click Finish4. Ene he eample code belo:
package entity; import
javax.persistence.EntityManager ;import javax.persistence.EntityManagerFactory ;import javax.persistence.Persistence; import org.apache.log4j.BasicConfigurator ;import org.apache.log4j.Level;import org.apache.log4j.Logger;
import org.junit.After;import org.junit.Before;import org.junit.Test; public class PersonTest { private EntityManagerFactory emf;
private EntityManager em;
@Before
public void initEmfAndEm() {BasicConfigurator.configure();
Logger.getLogger("org").setLevel(Level.ERROR);
emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");em = emf.createEntityManager();
@After public void cleanup() {
em.close();
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 6/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
@Test
public void emptyTest() {
1. When o'e finihed and i all compile, igh-click ihin he oce pane, elec Rn A:JUni Te2. Yo hold ee all geen3. If o do no, commen o he folloing line and eie he conole op
Logger.getLogger("org").setLevel(Level.ERROR);
Create Your First EntitFo hi eample e'll e a "op-don" appoach. Thi mean e'll ceae a Plain Old Jaa Objec (POJO) ih omeannoaion o indicae ho e an JPA o pei i. We'e leing he EniManage ake cae of ceaing he able inhe daabae fo .
Create a Simple Class
The folloing cla conain eehing o need o begin peiing i o a daabae:
Peon.jaa
package entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue ;
import javax.persistence.Id;
@Entit
public class Person {
@Id
@GeneratedValue
private int id;
private String firstName;
private char middleInitial;
private String lastName;
private String streetAddress1; private String streetAddress2;
private String city;
private String state;
private String zip;
public Person() {
public Person(final String fn, final char mi, final String ln,
final String sa1, final String sa2, final String city,
final String state, final String zip) {
setFirstName(fn);
setMiddleInitial(mi);
setLastName(ln);
setStreetAddress1(sa1);setStreetAddress2(sa2);
setCity(city);
setState(state);
setZip(zip);
public String getCity() {
return city;
public void setCity(final String city) {
this.city = city;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 7/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
en firstName;
pblic oid setFirstName(final Sing firstName) {
hi.firstName = firstName;
pblic in getId() {
en id;
pblic oid setId(final in id) { hi.id = id;
pblic Sing getLastName() {
en lastName;
pblic oid setLastName(final Sing lastName) {
hi.lastName = lastName;
pblic cha getMiddleInitial() {
en middleInitial;
pblic oid setMiddleInitial(final cha middleInitial) {
hi.middleInitial = middleInitial;
pblic Sing getState() {
en state;
pblic oid setState(final Sing state) {
hi.state = state;
pblic Sing getStreetAddress1() {
en streetAddress1;
pblic oid setStreetAddress1(final Sing streetAddress1) {
hi.streetAddress1 = streetAddress1;
pblic Sing getStreetAddress2() {
en streetAddress2;
pblic oid setStreetAddress2(final Sing streetAddress2) {
hi.streetAddress2 = streetAddress2;
pblic Sing getZip() { en zip;
pblic oid setZip(final Sing zip) {
hi.zip = zip;
Update persistence.m l Noe, fo o configaion hi ep i opional.
If o e libaie poided ecliel b JBo and Compan, hen o do no need o pdae o peience.ml. If o ae ing anohe endo o o an o make e ha o olion ill ok egadle of o peience
poide, add he folloing line o o peience.ml:
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 8/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
<class> entity.Person </class>
Y daed eiece. i :
<persistence>
<persistence-unit name="examplePersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<class> entity.Person </class>
<properties>
<propert name="hibernate.show_sql" value="false" />
<propert name="hibernate.format_sql" value="false" />
<propert name="hibernate.connection.driver_class"
value="org.hsqldb.jdbcDriver" />
<propert name="hibernate.connection.url"
value="jdbc:hsqldb:mem:mem:aname" />
<propert name="hibernate.connection.username" value="sa" />
<propert name="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect" />
<propert name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
Inserting and Quering N e eed dae i e ca, Pe.jaa. We i hae i ie ee, e ad eif ha he ee e ceaed ae i he daabae:PersonTest.jaa
package entity; import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertTrue; import java.util.List;
import javax.persistence.EntityManager ;import javax.persistence.EntityManagerFactory ;import javax.persistence.Persistence; import org.apache.log4j.BasicConfigurator ;import org.apache.log4j.Level;import org.apache.log4j.Logger;import org.junit.After;import org.junit.Before;import org.junit.Test; public class PersonTest { private final Person p1 = new Person("Brett", 'L', "Schuchert", "Street1",
"Street2", "City", "State", "Zip");
private final Person p2 = new Person("FirstName", 'K', "LastName", "Street1", "Street2", "City", "State", "Zip");
private EntityManagerFactory emf; private EntityManager em;
@Before public void initEmfAndEm() {
BasicConfigurator.configure(); Logger.getLogger("org").setLevel(Level.ERROR);
emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");em = emf.createEntityManager();
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 9/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
pblic oid cleanup()
em.close();
@SppeWaning("unchecked")
@Test
pblic oid insertAndRetrieve()
em.getTransaction().begin();
em.persist(p1);
em.persist(p2);
em.getTransaction().commit();
final Li<Person> list = em.createQuer("select p from Person p")
.getResultList();
assertEquals(2, list.sie());
fo (Person current : list)
final Sing firstName = current.getFirstName();
assertTrue(firstName.equals("Brett")
firstName.equals("FirstName"));
Re-run this test (the short-cut for this is Ctrl-Fll). Verif that everthing is green.
Add an Embedded EntitWhen we created Person we directl included address information into them. This is alright, but what if we want to useAddress in another class? Let's introduce a new entit, Address, and make it embedded. This means its fields will end upas columns in the table of the entit that contains it.
First, we'll create Address:
Address.jaa
package entit;
impo java.persistence.Embeddable;
@Embeddable
pblic cla Address piae Sing streetAddress1;
piae Sing streetAddress2;
piae Sing cit;
piae Sing state;
piae Sing ip;
pblic Address()
pblic Address(final Sing sa1, final Sing sa2, final Sing cit,
final Sing state, final Sing ip)
setStreetAddress1(sa1);
setStreetAddress2(sa2);
setCit(cit);
setState(state);setZip(ip);
pblic final Sing getCit()
en cit;
pblic final oid setCit(final Sing cit)
hi.cit = cit;
pblic final Sing getState()
en state;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 10/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
public final void setState(final String state) {
this.state = state;
public final String getStreetAddress1() {
return streetAddress1;
public final void setStreetAddress1(final String streetAddress1) {
this.streetAddress1 = streetAddress1;
public final String getStreetAddress2() {
return streetAddress2;
public final void setStreetAddress2(final String streetAddress2) {
this.streetAddress2 = streetAddress2;
public final String getZip() {
return zip;
public final void setZip(final String zip) {
this.zip = zip;
Net, e need to update Person (doing so ill cause our unit test class to no longer compile):Person.jaa
package entity;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue ;
import javax.persistence.Id;
@Entit public class Person {
@Id
@GeneratedValue
int id;
private String firstName;
private char middleInitial;
private String lastName;
@Embedded
private Address address;
public Person() {
public Person(final String fn, final char mi, final String ln,
final Address address) {
setFirstName(fn);
setMiddleInitial(mi);
setLastName(ln);
setAddress(address);
public String getFirstName() {
return firstName;
public void setFirstName(final String firstName) {
this.firstName = firstName;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 11/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
pblic in getId() {
en id;
pblic oid setId(final in id) {
hi.id = id;
pblic Sing getLastName() {
en lastName;
pblic oid setLastName(final Sing lastName) {
hi.lastName = lastName;
pblic cha getMiddleInitial() {
en middleInitial;
pblic oid setMiddleInitial(final cha middleInitial) {
hi.middleInitial = middleInitial;
pblic final Address getAddress() {
en address;
pblic final oid setAddress(final Address address) {
hi.address = address;
Se enogh, if o eie PeonTe.jaa, i no longe compile. Befoe e go an fhe, le' pdae i o ge i ocompile and hen eif ha he ni e ill pa.
Replace he folloing o line:
piae final Person p1 = ne Person("Brett", 'L', "Schuchert", "Street1",
"Street2", "City", "State", "Zip");
piae final Person p2 = ne Person("FirstName", 'K', "LastName",
"Street1", "Street2", "City", "State", "Zip");
ih he folloing fo line
piae final Address a1 = ne Address("A Rd.", "", "Dallas", "TX", "75001"
piae final Person p1 = ne Person("Brett", 'L', "Schuchert", a1);
piae final Address a2 = ne Address("B Rd.", "S2", "OkC", "OK", "73116")
piae final Person p2 = ne Person("FirstName", 'K', "LastName", a2);
Ren o e (Ctrl-F11) and make e eehing i all geen.
Ne, e an o eif ha he adde e pei i in he daabae. Updae he ni e mehod a follo:
PersonTest#insertAndRetriee
@SppeWaning("unchecked")
@Test
pblic oid insertAndRetrieve() {
em.getTransaction().begin();
em.persist(p1);
em.persist(p2);
em.getTransaction().commit();
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 12/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
final List<Person> list = em.createQuer("select p from Person p")
.getResultList();
assertEquals(2, list.sie());
for (Person current : list)
final String firstName = current.getFirstName();
final String streetAddress1 = current.getAddress()
.getStreetAddress1();
assertTrue(firstName.equals("Brett")
firstName.equals("FirstName"));
assertTrue(streetAddress1.equals("A Rd.")
streetAddress1.equals("B Rd."));
Run our program and make sure it's all green.
Add an Entit with a One to Man Relationship Now we'll make a compan. In this first tutorial we're keeping things simple so we'll just create a Compan that has a 1 toman relationship with People, who are its emploees:
Compan.java
package entit;
import java.util.ArraList;
import java.util.Collection;
import java.persistence.Embedded;
import java.persistence.Entit;
import java.persistence.GeneratedValue ;
import java.persistence.Id;
import java.persistence.OneToMan;
@Entit
public class Compan
@Id
@GeneratedValue
int id; private String name;
@Embedded
private Address address;
@OneToMan
private Collection<Person> emploees;
public Compan()
public Compan(final String name, final Address address,
final Collection<Person> emploees)
setName(name);
setAddress(address);
setEmploees(emploees);
public Address getAddress()
return address;
public void setAddress(final Address address)
this.address = address;
public Collection<Person> getEmploees()
if (emploees == null)
emploees = new ArraList<Person>();
return em lo ees
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 13/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
pblic oid setEmployees(final Collecion<Person> employees) {
hi.employees = employees;
pblic in getId() {
en id;
pblic oid setId(final in id) {
hi.id = id;
pblic Sing getName() {
en name;
pblic oid setName(final Sing name) {
hi.name = name;
pblic oid hire(final Person p) {
getEmployees().add(p);
pblic oid fire(final Person p) {getEmployees().remove(p);
Faco o Common Te CodeWe have some common initialiation we can move up into a base since we are going to have two tests classes,PersonTest and CompanTest:TestBase.jaa
package entity;
impo javax.persistence.EntityManager ;impo javax.persistence.EntityManagerFactory ;
impo javax.persistence.Persistence;
impo org.apache.log4j.BasicConfigurator ;
impo org.apache.log4j.Level;
impo org.apache.log4j.Logger;
impo org.junit.After;
impo org.junit.Before;
pblic cla TestBase {
poeced EntityManagerFactory emf;
poeced EntityManager em;
pblic TestBase() {
pe();
@Before
pblic oid initEmfAndEm() {
BasicConfigurator.configure();
Logge.getLogger("org").setLevel(Leel.ERROR);
emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");
em = emf.createEntityManager();
@After
pblic oid cleanup() {
em.close();
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 14/28
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 15/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
.
"select c from Company c where c.name=?1").setParameter(1,
"The Company").getSingleResult();
assertEquals("D Rd.", foundCompany.getAddress().getStreetAddress1());
// Note, e do not need an assert. Wh? the method getSingleResult()
// ill thro an eception if there is not eactl one
// object found. We'll research that in the second JPA tutorial.
Run this unit test and make sure it is all green before going on (right-click in the source pane, select Run As:JUnit Test)
If you'd like to run all of your tests, right-click on the test folder, select Run As:JUnit Test and eclipse will execute all oyour tests classes' test methods.
Hie ome peopleWe need to create some people and add them to the company. The PersonTest class already has some people. Rather than re-creating new people, let's update PersonTest to make those fields available. Update the a1, p1, a2, and p2 fieldsas follows:
public static List<Person> generatePersonObjects() {
final List<Person> people = new ArraList<Person>();
final Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");
final Person p1 = new Person("Brett", 'L', "Schuchert", a1);
final Address a2 = new Address("B Rd.", "S2", "OkC", "OK", "73116"); final Person p2 = new Person("FirstName", 'K', "LastName", a2);
people.add(p1);
people.add(p2);
return people;
You will also need to update the beginning of the method insertAndRetrieve from:
em.getTransaction().begin();
em.persist(p1);
em.persist(p2);
em.getTransaction().commit();
to:
final List<Person> people = generatePersonObjects();
em.getTransaction().begin();
for (Person p : people) {
em.persist(p);
em.getTransaction().commit();
Now we'll add a new test into CompanyTest to verify that we can hire people:
@SuppressWarnings("unchecked")
@Test
public void createCompanyAndHirePeople() {
final Company c1 = new Company();
c1.setName("The Company");
c1.setAddress(new Address("D Rd.", "", "Paris", "TX", "77382"));
List<Person> people = PersonTest.generatePersonObjects();
for (Person p : people) {
c1.hire(p);
em.getTransaction().begin();
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 16/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
for (Person p : people) {em.persist(p);
em.persist(c1);em.getTransaction().commit();
final List<Person> list = em.createQuery("select p from Person p")
.getResultList();assertEquals(2, list.size());
final Company foundCompany = (Company) em.createQuery(
"select c from Company c where c.name=?1").setParameter(1,
"The Company").getSingleResult();assertEquals(2, foundCompany.getEmployees().size());
Update persistence.m lAgain, gien o enionmen, hi ep i opional.
persistence.ml
<persistence>
<persistence-unit name="examplePersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<class> entity.Person </class>
<class> entity.Company </class>
<properties>
<propert name="hibernate.show_sql" value="false" />
<propert name="hibernate.format_sql" value="false" />
<propert name="hibernate.connection.driver_class"
value="org.hsqldb.jdbcDriver" />
<propert name="hibernate.connection.url"
value="jdbc:hsqldb:mem:mem:aname" />
<propert name="hibernate.connection.username"
value="sa" />
<propert name="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect" />
<propert name="hibernate.hbm2ddl.auto"
value="create" />
</properties>
</persistence-unit>
</persistence>
Make e eehing compile and n geen.
Make a Relationship Bi-Directional No e'e going o make e he Peon kno he Compan fo hich i ok. Thi i he "one" ide of a one oman elaionhip. We need o eplicil e hi ale and map i. We alo need o pdae he Compan @OneToManelaionhip o ha he Eni Manage kno i i a bi-diecional elaionhip ahe han j o nidiecionalelaionhip.
Fi e need o pdae Peon:Person.java
public class Person {
/** * Thi elaionhip i opional. Thi mean he daabae ill allo hi* elaionhip o be nll. I n o ha e i he defal ale o * e onl pecif i o docmen i eience.*/
@ManyToOne(optional = true) private Company job;
public Company getJob() {
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 17/28
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 18/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
Finall, we'll update CompanTest in several stages:
First, add a utilit method to retrieve companies b name:
piae Company findCompanyNamed(final EntityManager em, Sing name) {
en (Company) em.createQuery(
"select c from Company c where c.name=?1")
.setParameter(1, name).getSingleResult();
Add another support method to create a compan and hire a few people: piae Company createCompanyWithTwoEmployees() {
final Company c1 = ne Company();
c1.setName("The Company");
c1.setAddress(ne Address("D Rd.", "", "Paris", "TX", "77382"));
final Li<Person> people = PersonTest.generatePersonObjects();
fo (Person p : people) {
c1.hire(p);
em.getTransaction().begin();
fo (Person p : people) {
em.persist(p);
em.persist(c1);
em.getTransaction().commit();
en c1;
The method createCompan used to directl lookup a compan b name. Update the test method to use this privatemethod b changing this line:
final Company foundCompany = (Company) em.createQuery(
"select c from Company c where c.name=?1").setParameter(1,
"The Company").getSingleResult();
to:
final Company foundCompany = findCompanyNamed(em, "The Company");
Update the method createCompanAndHirePeopl b using the support method createCompanWithTwoEmploees():
@SppeWaning("unchecked")
@Test
pblic oid createCompanyAndHirePeople() {
createCompanyWithTwoEmployees();
final Li<Person> list = em.createQuery("select p from Person p")
.getResultList();
assertEquals(2, list.size());
final Company foundCompany = (Company) em.createQuery(
"select c from Company c where c.name=?1").setParameter(1,
"The Company").getSingleResult();
assertEquals(2, foundCompany.getEmployees().size());
Finall, add an additional unit test to hire and fire people:
@Test
pblic oid hireAndFire() {
final Company c1 = createCompanyWithTwoEmployees();
final Li<Person> people = PersonTest.generatePersonObjects();
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 19/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
em.getTransaction().begin();
fo (Person p : people) {
c1.fire(p);
em.persist(c1);
em.getTransaction().commit();
final Company foundCompany = findCompanyNamed(em, "The Company");
assertEquals(0, foundCompany.getEmployees().size());
Make e eehing compile and i geen.
Eecie
QeionDecibe ha he @Eni annoaion mean o a cla.Decibe ha he @Id annoaion mean o a cla.Decibe ha he @GeneaedVale mean o a claDecibe he diffeence beeen @Embeddable and @EmbeddedIn he peio ecion e menioned ing mappedB o le he conaine kno hi a a bi-diecional elaionhipinead of a nidiecional elaionhip. Wha doe hi een mean? Da an inance diagam ha old eplain hidiffeence.
Ne ClaRigh no he elaionhip beeen Peon and Compan i diec. Le' make ha a lile le diec. The Peon holdno hae a Job ih a ile, ala and emploeeId. The compan ill ha emploee a befoe. Thi pice decibe he
befoe and afe elaionhip.
In ode o efaco o he [aboe] "afe" pice conide ome of he folloing adice:
Create JobCeae a cla, Job, ih he folloing aibe:in idSing ile
Sing SalaSing emploeeNmbe Compan companPeon peon (added - fi diagram )
Update EmploeeThe Peon cla hold no longe hae a Compan aibe. Inead i ha a Job aibe.
Update CompanUpdae Compan.hie(). Change he ignae o ake a peon, ile, ala. I ill hen ceae he job, geneae anemploeeId, and e p all he elaionhip and en he job.
Updae he Compan.fie() a necea.
gue
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 20/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
M P J 1 . N .
Adanced: Fi c a a Daa Acce ObjecI , , .M D A O. U D'.
Enie Soce BaeAddress.jaa
package entity;
impo javax.persistence.Embeddable;
@Embeddable
pblic cla Address {
piae Sing streetAddress1;
piae Sing streetAddress2;
piae Sing city;
piae Sing state;
piae Sing zip;
pblic Address() {
pblic Address(final Sing sa1, final Sing sa2, final Sing city, final Sing state, final Sing zip) {
setStreetAddress1(sa1);
setStreetAddress2(sa2);
setCity(city);
setState(state);
setZip(zip);
pblic final Sing getCity() {
en city;
pblic final oid setCity(final Sing city) {
hi.city = city;
pblic final Sing getState() {
en state;
pblic final oid setState(final Sing state) {
hi.state = state;
pblic final Sing getStreetAddress1() {
en streetAddress1;
pblic final oid setStreetAddress1(final Sing streetAddress1) {
hi.streetAddress1 = streetAddress1;
pblic final Sing getStreetAddress2() {
en streetAddress2;
pblic final oid setStreetAddress2(final Sing streetAddress2) {
hi.streetAddress2 = streetAddress2;
pblic final Sing getZip() {
en zip;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 21/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
public final void setZip(final String zip) {
this.zip = zip;
Person.jaa
package entity;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue ;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entit
public class Person {
@Id
@GeneratedValue
int id;
private String firstName;
private char middleInitial;
private String lastName;
@ManyToOne(optional = true)
private Company job;
@Embedded
private Address address;
public Person() {
public Person(final String fn, final char mi, final String ln,
final Address address) {
setFirstName(fn);
setMiddleInitial(mi);
setLastName(ln);
setAddress(address);
public String getFirstName() {
return firstName;
public void setFirstName(final String firstName) {
this.firstName = firstName;
public int getId() {
return id;
public void setId(final int id) {
this.id = id;
public String getLastName() {
return lastName;
public void setLastName(final String lastName) {
this.lastName = lastName;
public char getMiddleInitial() {
return middleInitial;
public void setMiddleInitial(final char middleInitial) {
this.middleInitial = middleInitial;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 22/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
public final Address getAddress() {
return address;
public final void setAddress(final Address address) {
this.address = address;
public Company getJob() {
return job;
public void setJob(Company job) {
this.job = job;
public boolean equals(final Object rhs) {
if (rhs instanceof Person) {
final Person other = (Person) rhs;
return other.getLastName().equals(getLastName())
&& other.getFirstName().equals(getFirstName())
&& other.getMiddleInitial() == getMiddleInitial();
return false;
public int hashCode() {
return getLastName().hashCode() * getFirstName().hashCode()
* getMiddleInitial();
Compan.java
package entity;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue ;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entit
public class Company {
@Id
@GeneratedValue
int id;
private String name;
@Embedded private Address address;
@OneToMany(mappedBy = "job")
private Collection<Person> employees;
public Company() {
public Company(final String name, final Address address,
final Collection<Person> employees) {
setName(name);
setAddress(address);
setEmployees(employees);
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 23/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
public Address getAddress() {
return address;
public void setAddress(final Address address) {
this.address = address;
public Collection<Person> getEmployees() {
if (employees == null) {
employees = new ArraList<Person>();
return employees;
public void setEmployees(final Collection<Person> newStaff) {
// fire everbod
final Collection<Person> clone = new ArraList<Person>(employees);
for (Person p : clone) {
fire(p);
for (Person p : newStaff) {
hire(p);
public int getId() {
return id;
public void setId(final int id) {
this.id = id;
public String getName() {
return name;
public void setName(final String name) {
this.name = name;
public void hire(final Person p) {
getEmployees().add(p);
p.setJob(this);
public void fire(final Person p) {
getEmployees().remove(p);
p.setJob(null);
TestBase.jaa
package entity;
import javax.persistence.EntityManager ;
import javax.persistence.EntityManagerFactory ;
import javax.persistence.Persistence;
import org.apache.log4j.BasicConfigurator ;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 24/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
poeced EntityManagerFactory emf;
poeced EntityManager em;
pblic TestBase() {
pe();
@Before
pblic oid initEmfAndEm() {
BasicConfigurator.configure();
Logge.getLogger("org").setLevel(Leel.ERROR);
emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");
em = emf.createEntityManager();
@After
pblic oid cleanup() {
em.close();
CompanTest.java
package entity;
impo aic org.junit.Assert.assertEquals;
impo java.util.List;
impo javax.persistence.EntityManager ;
impo org.junit.Test;
pblic cla CompanyTest eend TestBase {
piae Company findCompanyNamed(final EntityManager em, Sing name) {
en (Company) em.createQuery(
"select c from Company c where c.name=?1")
.setParameter(1, name).getSingleResult();
@Test
pblic oid createCompany() {
final Company c1 = ne Company();
c1.setName("The Company");
c1.setAddress(ne Address("D Rd.", "", "Paris", "TX", "77382"));
em.getTransaction().begin();
em.persist(c1);
em.getTransaction().commit();
final Company foundCompany = findCompanyNamed(em, "The Company");
assertEquals("D Rd.", foundCompany.getAddress().getStreetAddress1());
// Note, e do not need an assert. Wh? the method getSingleResult() // ill thro an eception if there is not eactl one
// object found. We'll research that in the second JPA tutorial.
piae Company createCompanyWithTwoEmployees() {
final Company c1 = ne Company();
c1.setName("The Company");
c1.setAddress(ne Address("D Rd.", "", "Paris", "TX", "77382"));
final Li<Person> people = PersonTest.generatePersonObjects();
fo (Person p : people) {
c1.hire(p);
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 25/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
. .
fo (Person p : people) {
em.persist(p);
em.persist(c1);
em.getTransaction().commit();
en c1;
@SppeWaning("unchecked")
@Test
pblic oid createCompanyAndHirePeople() {
createCompanyWithTwoEmployees();
final Li<Person> list = em.createQuery("select p from Person p")
.getResultList();
assertEquals(2, list.size());
final Company foundCompany = (Company) em.createQuery(
"select c from Company c where c.name=?1").setParameter(1,
"The Company").getSingleResult();
assertEquals(2, foundCompany.getEmployees().size());
@Test
pblic oid hireAndFire() { final Company c1 = createCompanyWithTwoEmployees();
final Li<Person> people = PersonTest.generatePersonObjects();
em.getTransaction().begin();
fo (Person p : people) {
c1.fire(p);
em.persist(c1);
em.getTransaction().commit();
final Company foundCompany = findCompanyNamed(em, "The Company");
assertEquals(0, foundCompany.getEmployees().size());
PersonTest.jaa
package entity;
impo aic org.junit.Assert.assertEquals;
impo aic org.junit.Assert.assertTrue;
impo java.util.ArrayList;
impo java.util.List;
impo org.junit.Test;
pblic cla PersonTest eend TestBase {
pblic aic Li<Person> generatePersonObjects() { final Li<Person> people = ne AaLi<Person>();
final Address a1 = ne Address("A Rd.", "", "Dallas", "TX", "75001");
final Person p1 = ne Person("Brett", 'L', "Schuchert", a1);
final Address a2 = ne Address("B Rd.", "S2", "OkC", "OK", "73116");
final Person p2 = ne Person("FirstName", 'K', "LastName", a2);
people.add(p1);
people.add(p2);
en people;
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 26/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
@Test
pblic oid insertAndRetrieve()
final Li<Person> people = generatePersonObjects();
em.getTransaction().begin();
fo (Person p : people)
em.persist(p);
em.getTransaction().commit();
final Li<Person> list = em.createQuer("select p from Person p")
.getResultList();
assertEquals(2, list.sie());
fo (Person current : list)
final Sing firstName = current.getFirstName();
final Sing streetAddress1 = current.getAddress()
.getStreetAddress1();
assertTrue(firstName.equals("Brett")
firstName.equals("FirstName"));
assertTrue(streetAddress1.equals("A Rd.")
streetAddress1.equals("B Rd."));
FAQ
JPA Torial 1 - FAQ* What's the entit Manager? O . M @E. A / , ' . "Y "
Is hibernate using an in-memor database? H JPA. I . T H SQL.When do ou need a default constructor? S . I , . I (/), .
Annotations? A - - . T //. R . A '' (-, -, -).Compared to toplink: How are isolation levels handled? What kind of caching concerns do we have to worrabout? T .JEE source? D JB () B.Where does @Id go? (mehod or field?) I ' , JPA , ( ' '). I ' (I()), JPA , ' ' .Is there a reason @id is not private? B . (I )
When creating the job class, do we need equals() and hashcode()? In Compan.java there is a la-initialiation in getEmploees() . Wh? W , I (). L . T ( '' ).What's with the equals() method on Person? Y ' () ' . (-, , -, )How man times does it go to the database when ou have a one-to-man and ou retrieve the 'one' side. B, ('') , ( ' ) '' -- . Y =FT.EAGER (
). S ._=.Can ou turn off the 'caching' part of JPA? Y . L ' ' .How do ou know what ou set 'mappedB' to? U What happens if ou manipulate our objects outside of a transaction? I JSE , EM. S , , . I, , EM , .
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 27/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
huchert.ikispaces.com/JPA+Tutorial+1+-+Getting+Started
Be: Wha hae eaed i hi ia?Class responses://
E JPA JDBC .H U
//
Ree ei i he e e cieWhat does @Entit do?
// .T
//What does the @Id do ?
// @I .(, )
//What does the 'generatedValue' do ?
//
//What's embeddable vs. embedded?
//D . ( )
//
Da 1 Reie
Wha e eaed da . . .JU-- & (-)A & JU
EE M , , (!) /
( )
fee dbac fa he ca fa" "- , . ""
Wha e' d 3 ( )
L :JPA T 1 - BJPA T 1 - I SJPA T 1 - E P SJPA T 1 - P UJPA T 1 - F EJPA T 1 - E EJPA T 1 - E O M RJPA T 1 - M R B-
8/3/2019 Schuchert - JPA Tutorial 1 - Getting Started
http://slidepdf.com/reader/full/schuchert-jpa-tutorial-1-getting-started 28/28
7/12 schuchert - JPA Tutorial 1 - Getting Started
Help About Blog Pricing Privacy Terms Sppor Upgrade
Contributions to ht tp ://schuchert.wikispaces.com/ are licensed under a Creative Commons Attribution Share-Alike 2.5 License.
Portions not contributed by visitors are Copy right 2012 Tangient LLC.
Comments: please email: schuchert at ahoo dot com
JPA Tutorial 1 - ExercisesJPA Tutorial 1 - Entire Source BaseJPA Tutorial 1 - FAQ
<--Back