SlideShare a Scribd company logo
Andreas Martin - Page 1
Master of Science in Business Information Systems FHNW
Pre-Master Information Systems
3. Persistence Layer
Andreas Martin
3. Persistence Layer
http://www.flickr.com/photos/shandrew/3327258963
Andreas Martin - Page 2
Persistence Layer
 Object- Relational Mapping (ORM)
 Java Persistence API (JPA)
 Java Transaction API (JTA)
 Hands-on:
 Hands-on 1: JAVA PERSISTENCE
 Hands-on 2: MANAGING PERSISTENT OBJECTS
3. Persistence Layer
The Latte Macchiato «Layering» Principle
http://www.flickr.com/photos/tf28/4367660424
Presentation Layer
Goal: Display of information, processing /
forwarding of user interactions.
Technologies: JavaServer Faces (JSF), JavaServer
Pages (JSP), Servlets, etc.
Business (Logic) Layer
Goal: Reproduction of actions or «verbs» of the
application (buy a book, print an order, deliver a
book, etc.).
Technologies: Enterprise Java Beans (EJBs)
Persistence Layer
Goal: Reproduction of database attributes,
information or «nouns» in object / class attributes
(Object-Relational Mapping, ORM).
Technologies: Java Persistence API (JPA)
Object- Relational
Mapping (ORM)
http://www.flickr.com/photos/ellasdad/425813314
Andreas Martin - Page 5
JPA Specification at a Glance
 ORM: Mapping of java objects and database relations.
 Entity manager API: Database operations like: Create, Read,
Update, Delete (CRUD).
 Java Persistence Query Language (JPQL): Object oriented
query language.
 Java Transaction API (JTA): Transaction mechanism.
3. Persistence Layer
Source: Goncalves, 2010: Beginning Java™ EE 6 Platform with GlassFish™ 3 – Code (Apache-2.0 license): http://kenai.com/projects/beginningee6/
Andreas Martin - Page 6
Object-Relational Mapping (ORM)
3. Persistence Layer
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 7
Object-Relational Mapping (ORM)
 @Entity: declares a
database relation.
 @Id: defines the
primary key value(s).
 @GeneratedValue:
defines a value the will
be automatically
generated.
 @Column: can be used
to modify the standard
mapping behaviour.
3. Persistence Layer
Listing: A Simple Book Entity
@Entity
public class Book {
@Id @GeneratedValue
private Long id;
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// Constructors, getters, setters
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 8
Simple Example of a Book Entity
3. Persistence Layer
Listing: Simple Example of a Book Entity
@Entity
public class Book {
@Id
@GeneratedValue(strategy =
GenerationType.AUTO)
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
public Book() {
}
// Getters, setters
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 9
Simple Example of a Book Entity
3. Persistence Layer
Listing: Simple Example of a Book Entity
@Entity
public class Book {
@Id
@GeneratedValue(strategy =
GenerationType.AUTO)
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
public Book() {
}
// Getters, setters
}
Listing: Structure of the BOOK
Table
CREATE TABLE BOOK (
ID BIGINT NOT NULL,
TITLE VARCHAR(255),
PRICE DOUBLE(52, 0),
DESCRIPTION VARCHAR(255),
ISBN VARCHAR(255),
NBOFPAGE INTEGER,
ILLUSTRATIONS SMALLINT,
PRIMARY KEY (ID)
);
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 10
Querying Entities using JPQL and EntityManager
3. Persistence Layer
EntityManagerFactory emf = Persistence.createEntityManagerFactory("primary");
EntityManager em = emf.createEntityManager();
em.persist(book);
 The methods
persist() and find()
will be transferred
by the
EntityManager into
JDBC calls (INSERT or
SELECT SQL
statements).
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 11
Listing: A findBookByTitle Named Query
@Entity
@NamedQuery(name = "findBookWithTitleJava", query = "SELECT b
FROM Book b WHERE b.title =‘Java'")
public class Book {
@Id @GeneratedValue
private Long id;
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// Constructors, getters, setters
}
Querying Entities using JPQL and EntityManager
 Instead of using native SQL, it
is more sophisticated to use
JPQL:
 SELECT b FROM Book b
WHERE b.title = ‘Java‘;
 JPQL is similar to SQL, which adds
the object-point notation.
3. Persistence Layer
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 12
Hands-on-1
Java Persistence
3. Persistence Layer
Andreas Martin - Page 13
Predefined Projects - Hands-on Projects @ GitHub
…will be used for all the hands-on’s
1. First download “Hands-on Projects @ GitHub” ZIP- file from
Moodle and extract it into a folder.
2. Import predefined projects in Eclipse:
3. Persistence Layer
Andreas Martin - Page 14
Database Connection
…will be used for the next two hands-on’s
 Create or modify the persistence.xml file:
 Choose another student ‘number’
to avoid overwriting.
3. Persistence Layer
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.username" value="premscis"/>
<property name="hibernate.connection.password" value="premscis"/>
<property name="hibernate.connection.url" value="jdbc:mysql://mature.iwi.wirtschaft.fhnw.ch:80/student0"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Andreas Martin - Page 15
Hands-on 1: Overview
 Now we know what an entity or the entity manager is.
 In this hands-on we are going to write a small application,
which stores an entity into a database.
 Create a Book entity and a Main class including a main
method, that stores a book entry into our MySQL database
(use the premscis scheme).
 Use the predefined maven project and watch out the pre-
configurations.
3. Persistence Layer
Andreas Martin - Page 16
Hands-on 1
1. Import (or create from blueprint) the hands-on-1 project. All
the source code will be placed into the
ch.fhnw.mscbis.premscis.handson1 package.
2. Create a Book entity with the following attributes: id,
title, price, description, isbn,
numberOfPages and illustrations. Choose the right
datatypes.
3. Generate Getter & Setter methods.
3. Persistence Layer
Andreas Martin - Page 17
Hands-on 1
4. Create a Main class and a main method where you create a
book.
3. Persistence Layer
// Create a book
EntityManagerFactory emf = Persistence.createEntityManagerFactory("primary");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
em.close();
emf.close();
Object- Relational
Mapping (ORM)
http://www.flickr.com/photos/ellasdad/425813314
@Annotations
Andreas Martin - Page 19
@Table
 @Table(name = ""): is used to
define the name of the
database table.
 Btw.:
@javax.persistence.Table
would be the full path to the
annotation, we can use the
short form in combination
with an include.
3. Persistence Layer
Listing: The Book Entity Being
Mapped to a T_BOOK Table
@Entity
@Table(name = "t_book")
public class Book {
@Id
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
public Book() {
}
// Getters and setters
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 20
@SecondaryTable
3. Persistence Layer
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 21
@SecondaryTable
3. Persistence Layer
Listing: Attributes of the Address Entity Mapped in Three Different Tables
@Entity
@SecondaryTables( {
@SecondaryTable(name = "city"),
@SecondaryTable(name = "country")
})
public class Address {
@Id
private Long id;
private String street1;
private String street2;
@Column(table = "city")
private String city;
@Column(table = "city")
private String state;
@Column(table = "city")
private String zipcode;
@Column(table = "country")
private String country;
// Constructors, getters, setters
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 22
Composite Primary Key using @EmbeddedId
3. Persistence Layer
Listing: DDL of the NEWS Table with a Composite Primary Key
create table NEWS (
CONTENT VARCHAR(255),
TITLE VARCHAR(255) not null,
LANGUAGE VARCHAR(255) not null,
primary key (TITLE, LANGUAGE)
);
Listing: The Entity Embeds the
Primary Key Class with @EmbeddedId
@Entity
public class News {
@EmbeddedId
private NewsId id;
private String content;
// …
}
Listing: The Primary Key Class Is
Annotated with @Embeddable
@Embeddable
public class NewsId {
private String title;
private String language;
// …
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 23
Relationship Mapping
3. Persistence Layer
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Annotation Direction
@OneToOne Unidirectional
@OneToOne Bidirectional
@OneToMany Unidirectional
@ManyToOne / @OneToMany Bidirectional
@ManyToOne Unidirectional
@ManyToMany Unidirectional
@ManyToMany Bidirectional
All possible mappings:
Andreas Martin - Page 24
@OneToOne
3. Persistence Layer
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Listing: The Customer Entity
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@OneToOne
@JoinColumn(name = "address_fk")
private Address address;
// Constructors, getters, setters
}
Listing: An Address Entity
@Entity
public class Address {
@Id @GeneratedValue
private Long id;
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;
@OneToOne(mappedBy = "address")
private Customer customer;
// Constructors, getters, setters
}
Andreas Martin - Page 25
@OneToMany Unidirectional
3. Persistence Layer
Listing: The Order Entity with a Join Column
@Entity
public class Order {
@Id @GeneratedValue
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "order_fk")
private List<OrderLine> orderLines;
// Constructors, getters, setters
}
Listing: An OrderLine
@Entity
@Table(name = "order_line")
public class OrderLine {
@Id @GeneratedValue
private Long id;
private String item;
private Double unitPrice;
private Integer quantity;
// Constructors, getters, setters
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 26
@ManyToMany Bidirectional – read & write
3. Persistence Layer
Listing: One Artist Appears on Several CD Albums
@Entity
public class Artist {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "jnd_art_cd",
joinColumns = @JoinColumn(name = "artist_fk"),
inverseJoinColumns = @JoinColumn(name = "cd_fk"))
private List<CD> appearsOnCDs;
// Constructors, getters, setters
}
Listing: One CD is Created by Several Artists
@Entity
public class CD {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "jnd_art_cd",
joinColumns = @JoinColumn(name = "cd_fk"),
inverseJoinColumns = @JoinColumn(name = "artist_fk"))
private List<Artist> createdByArtists;
// Constructors, getters, setters
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 27
Managing Persistent Objects
3. Persistence Layer
Andreas Martin - Page 28
Recap our Hands-on 1
3. Persistence Layer
Listing: A Main Class Persisting and Retrieving a Book Entity
public class Main {
public static void main(String[] args) {
// 1-Create an instance of the Book entity
Book book = new Book();
book.setId(1234L);
book.setTitle("The Hitchhiker's Guide to the Galaxy");
book.setPrice(12.5F);
book.setDescription("Science fiction created by Douglas Adams.");
book.setIsbn("1-84023-742-2");
book.setNbOfPage(354);
book.setIllustrations(false);
// 2-Get an entity manager and a transaction
EntityManagerFactory emf =
Persistence.createEntityManagerFactory(«primary");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
// 3-Persist the book to the database
tx.begin();
em.persist(book);
tx.commit();
// 4-Retrieve the book by its identifier
book = em.find(Book.class, 1234L);
System.out.println(book);
em.close();
emf.close();
}
}
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 29
Persisting an Entity
3. Persistence Layer
Listing: Persisting a Customer with an Address
EntityManager em = …;
Customer customer = new Customer("Antony", "Balla", "tballa@mail.com");
Address address = new Address("Ritherdon Rd", "London", "8QE", "UK");
customer.setAddress(address);
tx.begin();
em.persist(customer);
em.persist(address);
tx.commit();
assertNotNull(customer.getId());
assertNotNull(address.getId());
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 30
JPQL
3. Persistence Layer
Andreas Martin - Page 31
UPDATE <entity name> [[AS] <identification variable>]
SET <update statement> {, <update statement>}*
[WHERE <conditional expression>]
DELETE FROM <entity name> [[AS] <identification var.>]
[WHERE <conditional expression>]
JPQL
SELECT- Syntax
DELETE- Syntax
UPDATE- Syntax
 The JPQL syntax is
comparable to the SQL
syntax is used in a MySQL or
Apache Derby environment.
 Extensions in JPQL e.g.:
3. Persistence Layer
Source: Goncalves, 2010: Beginning Java™ EE 6 Platform with GlassFish™ 3 – Code (Apache-2.0 license): http://kenai.com/projects/beginningee6/
SELECT <expression>
FROM <clause>
[WHERE <conditional expression>]
[ORDER BY <clause>]
[GROUP BY <clause>]
[HAVING <clause>]
SELECT CASE b.author WHEN 'Martin'
THEN b.price * 1.5
ELSE b.price * 0.8
END
FROM Book b
Andreas Martin - Page 32
Named Queries
 Named Queries like Dynamic Queries:
Query query = em.createNamedQuery("findAll");
List<Customer> customers = query.getResultList();
 as Named Typed Query:
TypedQuery<Customer> query = em.createNamedQuery("findAll", Customer.class);
List<Customer> customers = query.getResultList();
 and including parameters
Query query = em.createNamedQuery("findWithParam");
query.setParameter("fname", "Vincent");
List<Customer> customers = query.getResultList();
3. Persistence Layer
Listing: The Customer Entity Defining Named Queries
@Entity
@NamedQueries( {
@NamedQuery(name = "findAll", query="select c from Customer c"),
@NamedQuery(name = "findVincent", query="select c from Customer c where c.firstName
= 'Vincent'"),
@NamedQuery(name = "findWithParam", query="select c from Customer c where
c.firstName = :fname") })
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName; /* etc. */ }
Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
Andreas Martin - Page 33
Hands-on 2
MANAGING PERSISTENT OBJECTS
3. Persistence Layer
Based on: Goncalves, 2010: Beginning Java™ EE 6 Platform with GlassFish™ 3
Andreas Martin - Page 34
Hands-on 2
1. Import the «hands-on-2» project.
2. Create the following entities: Address and Customer
 Fields of Address: id, street1, city, zipcode und country.
 Fields of Customer: id, firstName, lastName, email und address.
 Please give the entities a unique table name.
3. Write a main method in a Main class and enter some data
into the database.
3. Persistence Layer

More Related Content

What's hot (20)

DOCX
Java interview questions and answers
Krishnaov
 
PPS
Jdbc api
kamal kotecha
 
PPTX
Schema webinar
Gary Sherman
 
PPTX
Schema201 webinar
Gary Sherman
 
PPTX
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
PDF
Hibernate Advance Interview Questions
Rudra Garnaik, PMI-ACP®
 
PPT
Complex Data Binding
Doncho Minkov
 
PPTX
Introduction to JPA Framework
Collaboration Technologies
 
PPTX
Getting started with entity framework
Lushanthan Sivaneasharajah
 
ODP
Hibernate Developer Reference
Muthuselvam RS
 
DOCX
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
PDF
Hibernate Tutorial
Syed Shahul
 
PDF
Mvc acchitecture
laxmi.katkar
 
PDF
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPT
hibernate with JPA
Mohammad Faizan
 
PPTX
Poject documentation deepak
chetankane
 
PPS
Ado.net session04
Niit Care
 
PDF
Mallet
Shatakirti Er
 
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Java interview questions and answers
Krishnaov
 
Jdbc api
kamal kotecha
 
Schema webinar
Gary Sherman
 
Schema201 webinar
Gary Sherman
 
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
Hibernate Advance Interview Questions
Rudra Garnaik, PMI-ACP®
 
Complex Data Binding
Doncho Minkov
 
Introduction to JPA Framework
Collaboration Technologies
 
Getting started with entity framework
Lushanthan Sivaneasharajah
 
Hibernate Developer Reference
Muthuselvam RS
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
Hibernate Tutorial
Syed Shahul
 
Mvc acchitecture
laxmi.katkar
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
JDBC – Java Database Connectivity
Information Technology
 
hibernate with JPA
Mohammad Faizan
 
Poject documentation deepak
chetankane
 
Ado.net session04
Niit Care
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 

Viewers also liked (20)

PPT
La revolución digital: tendencias en los medios y en la publicidad | Víctor K...
EBEDominicana
 
PDF
Directorios para pyme
Govern Consulting
 
PDF
Energy And Natural Resources, Energy News, Natural Resources, Solar Power
Corp LiveWire
 
PPTX
Partes de-un-celular
Georgette González
 
PDF
An Integrated Management Supervisor for End-to-End Management of Heterogeneou...
Alpen-Adria-Universität
 
PDF
Club de beneficios Patria Quemera
Ofertona-Division-Corporativa
 
DOCX
Planes de negocios
giacop19
 
PDF
IC 2010 Info Pack
Thomas Müller
 
PDF
ViSalus Policies Procedures UK 2013
ViSalus Shakes
 
PPT
Presentación actividades de formación 2014 2015-1
CPR Oviedo
 
PPS
Native Advertising at Scale
Matt O'Neill
 
PDF
Putera Sampoerna Foundation Report Quarter 1 2009
Putera Sampoerna Foundation
 
PDF
BIBLIA CATOLICA, NUEVO TESTAMENTO, CARTAS DE JUAN, PARTE 23 DE 27
sifexol
 
PDF
Jiri_Ptacek_Blackbelt_Case_study_Certified
Jiri Ptacek
 
PDF
Guía dental SANITAS Barcelona 2013
Comercial-APPSalud
 
PDF
자동인식&스마트SCM(MONTHLY AIDC+SMART SCM) 2013년 2월호
고양뉴스
 
PPTX
Ge presentación grupo 4
Javier Alfonso Villa Torres
 
PDF
Politica2.cero: Pablo Iglesias, email marketing en "Estrategias de Engagement...
Candedo
 
PPTX
Exposicon formacion critica
NicksonxD
 
PDF
EY Global Market Outlook 2016 - Trends in Real Estate Private Equity
Thorsten Lederer 托尔斯滕
 
La revolución digital: tendencias en los medios y en la publicidad | Víctor K...
EBEDominicana
 
Directorios para pyme
Govern Consulting
 
Energy And Natural Resources, Energy News, Natural Resources, Solar Power
Corp LiveWire
 
Partes de-un-celular
Georgette González
 
An Integrated Management Supervisor for End-to-End Management of Heterogeneou...
Alpen-Adria-Universität
 
Club de beneficios Patria Quemera
Ofertona-Division-Corporativa
 
Planes de negocios
giacop19
 
IC 2010 Info Pack
Thomas Müller
 
ViSalus Policies Procedures UK 2013
ViSalus Shakes
 
Presentación actividades de formación 2014 2015-1
CPR Oviedo
 
Native Advertising at Scale
Matt O'Neill
 
Putera Sampoerna Foundation Report Quarter 1 2009
Putera Sampoerna Foundation
 
BIBLIA CATOLICA, NUEVO TESTAMENTO, CARTAS DE JUAN, PARTE 23 DE 27
sifexol
 
Jiri_Ptacek_Blackbelt_Case_study_Certified
Jiri Ptacek
 
Guía dental SANITAS Barcelona 2013
Comercial-APPSalud
 
자동인식&스마트SCM(MONTHLY AIDC+SMART SCM) 2013년 2월호
고양뉴스
 
Ge presentación grupo 4
Javier Alfonso Villa Torres
 
Politica2.cero: Pablo Iglesias, email marketing en "Estrategias de Engagement...
Candedo
 
Exposicon formacion critica
NicksonxD
 
EY Global Market Outlook 2016 - Trends in Real Estate Private Equity
Thorsten Lederer 托尔斯滕
 
Ad

Similar to 2014 Pre-MSc-IS-3 Persistence Layer (20)

PDF
Ejb3 Struts Tutorial En
Ankur Dongre
 
PDF
Ejb3 Struts Tutorial En
Ankur Dongre
 
PDF
Hibernate An Introduction
Nguyen Cao
 
PPT
Patni Hibernate
patinijava
 
PDF
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
CODE WHITE GmbH
 
PDF
backend
tutorialsruby
 
PDF
backend
tutorialsruby
 
PDF
JavaScript Miller Columns
Jonathan Fine
 
PPT
Introducing Struts 2
wiradikusuma
 
PDF
Java Deserialization Vulnerabilities - The Forgotten Bug Class
CODE WHITE GmbH
 
ZIP
Rails and alternative ORMs
Jonathan Dahl
 
PDF
2014 Pre-MSc-IS-4 Business Logic Layer
andreasmartin
 
PDF
Lift Framework
Jeffrey Groneberg
 
PPTX
Java scriptforjavadev part2a
Makarand Bhatambarekar
 
PDF
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
DOCX
Prg421
john roy
 
DOC
Assignment Examples Final 07 Oct
Sriram Raj
 
PPT
Krazykoder struts2 spring_hibernate
Krazy Koder
 
PDF
Struts database access
Abass Ndiaye
 
PPT
Reversing JavaScript
Roberto Suggi Liverani
 
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ankur Dongre
 
Hibernate An Introduction
Nguyen Cao
 
Patni Hibernate
patinijava
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
CODE WHITE GmbH
 
backend
tutorialsruby
 
backend
tutorialsruby
 
JavaScript Miller Columns
Jonathan Fine
 
Introducing Struts 2
wiradikusuma
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
CODE WHITE GmbH
 
Rails and alternative ORMs
Jonathan Dahl
 
2014 Pre-MSc-IS-4 Business Logic Layer
andreasmartin
 
Lift Framework
Jeffrey Groneberg
 
Java scriptforjavadev part2a
Makarand Bhatambarekar
 
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
Prg421
john roy
 
Assignment Examples Final 07 Oct
Sriram Raj
 
Krazykoder struts2 spring_hibernate
Krazy Koder
 
Struts database access
Abass Ndiaye
 
Reversing JavaScript
Roberto Suggi Liverani
 
Ad

More from andreasmartin (7)

PDF
A Case Modelling Language for Process Variant Management in Case-based Reasoning
andreasmartin
 
PDF
2014 Pre-MSc-IS-6 Presentation Layer
andreasmartin
 
PDF
2014 Pre-MSc-IS-5 Process Layer
andreasmartin
 
PDF
2014 Pre-MSc-IS-2 Infrastructure
andreasmartin
 
PDF
2014 Pre-MSc-IS-1 Java Enterprise Edition and Information Systems Layering
andreasmartin
 
PDF
2014 Pre-MSc-IS-0 Information Systems Modelling and Design
andreasmartin
 
PDF
Integrating an Enterprise Architecture Ontology in a Case-based Reasoning App...
andreasmartin
 
A Case Modelling Language for Process Variant Management in Case-based Reasoning
andreasmartin
 
2014 Pre-MSc-IS-6 Presentation Layer
andreasmartin
 
2014 Pre-MSc-IS-5 Process Layer
andreasmartin
 
2014 Pre-MSc-IS-2 Infrastructure
andreasmartin
 
2014 Pre-MSc-IS-1 Java Enterprise Edition and Information Systems Layering
andreasmartin
 
2014 Pre-MSc-IS-0 Information Systems Modelling and Design
andreasmartin
 
Integrating an Enterprise Architecture Ontology in a Case-based Reasoning App...
andreasmartin
 

Recently uploaded (20)

PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PDF
Basics of Electronics for IOT(actuators ,microcontroller etc..)
arnavmanesh
 
PDF
Per Axbom: The spectacular lies of maps
Nexer Digital
 
PDF
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Basics of Electronics for IOT(actuators ,microcontroller etc..)
arnavmanesh
 
Per Axbom: The spectacular lies of maps
Nexer Digital
 
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
The Future of Artificial Intelligence (AI)
Mukul
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 

2014 Pre-MSc-IS-3 Persistence Layer

  • 1. Andreas Martin - Page 1 Master of Science in Business Information Systems FHNW Pre-Master Information Systems 3. Persistence Layer Andreas Martin 3. Persistence Layer http://www.flickr.com/photos/shandrew/3327258963
  • 2. Andreas Martin - Page 2 Persistence Layer  Object- Relational Mapping (ORM)  Java Persistence API (JPA)  Java Transaction API (JTA)  Hands-on:  Hands-on 1: JAVA PERSISTENCE  Hands-on 2: MANAGING PERSISTENT OBJECTS 3. Persistence Layer
  • 3. The Latte Macchiato «Layering» Principle http://www.flickr.com/photos/tf28/4367660424 Presentation Layer Goal: Display of information, processing / forwarding of user interactions. Technologies: JavaServer Faces (JSF), JavaServer Pages (JSP), Servlets, etc. Business (Logic) Layer Goal: Reproduction of actions or «verbs» of the application (buy a book, print an order, deliver a book, etc.). Technologies: Enterprise Java Beans (EJBs) Persistence Layer Goal: Reproduction of database attributes, information or «nouns» in object / class attributes (Object-Relational Mapping, ORM). Technologies: Java Persistence API (JPA)
  • 5. Andreas Martin - Page 5 JPA Specification at a Glance  ORM: Mapping of java objects and database relations.  Entity manager API: Database operations like: Create, Read, Update, Delete (CRUD).  Java Persistence Query Language (JPQL): Object oriented query language.  Java Transaction API (JTA): Transaction mechanism. 3. Persistence Layer Source: Goncalves, 2010: Beginning Java™ EE 6 Platform with GlassFish™ 3 – Code (Apache-2.0 license): http://kenai.com/projects/beginningee6/
  • 6. Andreas Martin - Page 6 Object-Relational Mapping (ORM) 3. Persistence Layer Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 7. Andreas Martin - Page 7 Object-Relational Mapping (ORM)  @Entity: declares a database relation.  @Id: defines the primary key value(s).  @GeneratedValue: defines a value the will be automatically generated.  @Column: can be used to modify the standard mapping behaviour. 3. Persistence Layer Listing: A Simple Book Entity @Entity public class Book { @Id @GeneratedValue private Long id; @Column(nullable = false) private String title; private Float price; @Column(length = 2000) private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations; // Constructors, getters, setters } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 8. Andreas Martin - Page 8 Simple Example of a Book Entity 3. Persistence Layer Listing: Simple Example of a Book Entity @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String title; private Float price; private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations; public Book() { } // Getters, setters } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 9. Andreas Martin - Page 9 Simple Example of a Book Entity 3. Persistence Layer Listing: Simple Example of a Book Entity @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String title; private Float price; private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations; public Book() { } // Getters, setters } Listing: Structure of the BOOK Table CREATE TABLE BOOK ( ID BIGINT NOT NULL, TITLE VARCHAR(255), PRICE DOUBLE(52, 0), DESCRIPTION VARCHAR(255), ISBN VARCHAR(255), NBOFPAGE INTEGER, ILLUSTRATIONS SMALLINT, PRIMARY KEY (ID) ); Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 10. Andreas Martin - Page 10 Querying Entities using JPQL and EntityManager 3. Persistence Layer EntityManagerFactory emf = Persistence.createEntityManagerFactory("primary"); EntityManager em = emf.createEntityManager(); em.persist(book);  The methods persist() and find() will be transferred by the EntityManager into JDBC calls (INSERT or SELECT SQL statements). Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 11. Andreas Martin - Page 11 Listing: A findBookByTitle Named Query @Entity @NamedQuery(name = "findBookWithTitleJava", query = "SELECT b FROM Book b WHERE b.title =‘Java'") public class Book { @Id @GeneratedValue private Long id; @Column(nullable = false) private String title; private Float price; @Column(length = 2000) private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations; // Constructors, getters, setters } Querying Entities using JPQL and EntityManager  Instead of using native SQL, it is more sophisticated to use JPQL:  SELECT b FROM Book b WHERE b.title = ‘Java‘;  JPQL is similar to SQL, which adds the object-point notation. 3. Persistence Layer Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 12. Andreas Martin - Page 12 Hands-on-1 Java Persistence 3. Persistence Layer
  • 13. Andreas Martin - Page 13 Predefined Projects - Hands-on Projects @ GitHub …will be used for all the hands-on’s 1. First download “Hands-on Projects @ GitHub” ZIP- file from Moodle and extract it into a folder. 2. Import predefined projects in Eclipse: 3. Persistence Layer
  • 14. Andreas Martin - Page 14 Database Connection …will be used for the next two hands-on’s  Create or modify the persistence.xml file:  Choose another student ‘number’ to avoid overwriting. 3. Persistence Layer <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="primary" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.username" value="premscis"/> <property name="hibernate.connection.password" value="premscis"/> <property name="hibernate.connection.url" value="jdbc:mysql://mature.iwi.wirtschaft.fhnw.ch:80/student0"/> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
  • 15. Andreas Martin - Page 15 Hands-on 1: Overview  Now we know what an entity or the entity manager is.  In this hands-on we are going to write a small application, which stores an entity into a database.  Create a Book entity and a Main class including a main method, that stores a book entry into our MySQL database (use the premscis scheme).  Use the predefined maven project and watch out the pre- configurations. 3. Persistence Layer
  • 16. Andreas Martin - Page 16 Hands-on 1 1. Import (or create from blueprint) the hands-on-1 project. All the source code will be placed into the ch.fhnw.mscbis.premscis.handson1 package. 2. Create a Book entity with the following attributes: id, title, price, description, isbn, numberOfPages and illustrations. Choose the right datatypes. 3. Generate Getter & Setter methods. 3. Persistence Layer
  • 17. Andreas Martin - Page 17 Hands-on 1 4. Create a Main class and a main method where you create a book. 3. Persistence Layer // Create a book EntityManagerFactory emf = Persistence.createEntityManagerFactory("primary"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(book); tx.commit(); em.close(); emf.close();
  • 19. Andreas Martin - Page 19 @Table  @Table(name = ""): is used to define the name of the database table.  Btw.: @javax.persistence.Table would be the full path to the annotation, we can use the short form in combination with an include. 3. Persistence Layer Listing: The Book Entity Being Mapped to a T_BOOK Table @Entity @Table(name = "t_book") public class Book { @Id private Long id; private String title; private Float price; private String description; private String isbn; private Integer nbOfPage; private Boolean illustrations; public Book() { } // Getters and setters } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 20. Andreas Martin - Page 20 @SecondaryTable 3. Persistence Layer Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 21. Andreas Martin - Page 21 @SecondaryTable 3. Persistence Layer Listing: Attributes of the Address Entity Mapped in Three Different Tables @Entity @SecondaryTables( { @SecondaryTable(name = "city"), @SecondaryTable(name = "country") }) public class Address { @Id private Long id; private String street1; private String street2; @Column(table = "city") private String city; @Column(table = "city") private String state; @Column(table = "city") private String zipcode; @Column(table = "country") private String country; // Constructors, getters, setters } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 22. Andreas Martin - Page 22 Composite Primary Key using @EmbeddedId 3. Persistence Layer Listing: DDL of the NEWS Table with a Composite Primary Key create table NEWS ( CONTENT VARCHAR(255), TITLE VARCHAR(255) not null, LANGUAGE VARCHAR(255) not null, primary key (TITLE, LANGUAGE) ); Listing: The Entity Embeds the Primary Key Class with @EmbeddedId @Entity public class News { @EmbeddedId private NewsId id; private String content; // … } Listing: The Primary Key Class Is Annotated with @Embeddable @Embeddable public class NewsId { private String title; private String language; // … } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 23. Andreas Martin - Page 23 Relationship Mapping 3. Persistence Layer Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7 Annotation Direction @OneToOne Unidirectional @OneToOne Bidirectional @OneToMany Unidirectional @ManyToOne / @OneToMany Bidirectional @ManyToOne Unidirectional @ManyToMany Unidirectional @ManyToMany Bidirectional All possible mappings:
  • 24. Andreas Martin - Page 24 @OneToOne 3. Persistence Layer Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7 Listing: The Customer Entity @Entity public class Customer { @Id @GeneratedValue private Long id; private String firstName; private String lastName; private String email; private String phoneNumber; @OneToOne @JoinColumn(name = "address_fk") private Address address; // Constructors, getters, setters } Listing: An Address Entity @Entity public class Address { @Id @GeneratedValue private Long id; private String street1; private String street2; private String city; private String state; private String zipcode; private String country; @OneToOne(mappedBy = "address") private Customer customer; // Constructors, getters, setters }
  • 25. Andreas Martin - Page 25 @OneToMany Unidirectional 3. Persistence Layer Listing: The Order Entity with a Join Column @Entity public class Order { @Id @GeneratedValue private Long id; @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @OneToMany(fetch = FetchType.EAGER) @JoinColumn(name = "order_fk") private List<OrderLine> orderLines; // Constructors, getters, setters } Listing: An OrderLine @Entity @Table(name = "order_line") public class OrderLine { @Id @GeneratedValue private Long id; private String item; private Double unitPrice; private Integer quantity; // Constructors, getters, setters } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 26. Andreas Martin - Page 26 @ManyToMany Bidirectional – read & write 3. Persistence Layer Listing: One Artist Appears on Several CD Albums @Entity public class Artist { @Id @GeneratedValue private Long id; private String firstName; private String lastName; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "jnd_art_cd", joinColumns = @JoinColumn(name = "artist_fk"), inverseJoinColumns = @JoinColumn(name = "cd_fk")) private List<CD> appearsOnCDs; // Constructors, getters, setters } Listing: One CD is Created by Several Artists @Entity public class CD { @Id @GeneratedValue private Long id; private String title; private Float price; private String description; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "jnd_art_cd", joinColumns = @JoinColumn(name = "cd_fk"), inverseJoinColumns = @JoinColumn(name = "artist_fk")) private List<Artist> createdByArtists; // Constructors, getters, setters } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 27. Andreas Martin - Page 27 Managing Persistent Objects 3. Persistence Layer
  • 28. Andreas Martin - Page 28 Recap our Hands-on 1 3. Persistence Layer Listing: A Main Class Persisting and Retrieving a Book Entity public class Main { public static void main(String[] args) { // 1-Create an instance of the Book entity Book book = new Book(); book.setId(1234L); book.setTitle("The Hitchhiker's Guide to the Galaxy"); book.setPrice(12.5F); book.setDescription("Science fiction created by Douglas Adams."); book.setIsbn("1-84023-742-2"); book.setNbOfPage(354); book.setIllustrations(false); // 2-Get an entity manager and a transaction EntityManagerFactory emf = Persistence.createEntityManagerFactory(«primary"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); // 3-Persist the book to the database tx.begin(); em.persist(book); tx.commit(); // 4-Retrieve the book by its identifier book = em.find(Book.class, 1234L); System.out.println(book); em.close(); emf.close(); } } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 29. Andreas Martin - Page 29 Persisting an Entity 3. Persistence Layer Listing: Persisting a Customer with an Address EntityManager em = …; Customer customer = new Customer("Antony", "Balla", "[email protected]"); Address address = new Address("Ritherdon Rd", "London", "8QE", "UK"); customer.setAddress(address); tx.begin(); em.persist(customer); em.persist(address); tx.commit(); assertNotNull(customer.getId()); assertNotNull(address.getId()); Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 30. Andreas Martin - Page 30 JPQL 3. Persistence Layer
  • 31. Andreas Martin - Page 31 UPDATE <entity name> [[AS] <identification variable>] SET <update statement> {, <update statement>}* [WHERE <conditional expression>] DELETE FROM <entity name> [[AS] <identification var.>] [WHERE <conditional expression>] JPQL SELECT- Syntax DELETE- Syntax UPDATE- Syntax  The JPQL syntax is comparable to the SQL syntax is used in a MySQL or Apache Derby environment.  Extensions in JPQL e.g.: 3. Persistence Layer Source: Goncalves, 2010: Beginning Java™ EE 6 Platform with GlassFish™ 3 – Code (Apache-2.0 license): http://kenai.com/projects/beginningee6/ SELECT <expression> FROM <clause> [WHERE <conditional expression>] [ORDER BY <clause>] [GROUP BY <clause>] [HAVING <clause>] SELECT CASE b.author WHEN 'Martin' THEN b.price * 1.5 ELSE b.price * 0.8 END FROM Book b
  • 32. Andreas Martin - Page 32 Named Queries  Named Queries like Dynamic Queries: Query query = em.createNamedQuery("findAll"); List<Customer> customers = query.getResultList();  as Named Typed Query: TypedQuery<Customer> query = em.createNamedQuery("findAll", Customer.class); List<Customer> customers = query.getResultList();  and including parameters Query query = em.createNamedQuery("findWithParam"); query.setParameter("fname", "Vincent"); List<Customer> customers = query.getResultList(); 3. Persistence Layer Listing: The Customer Entity Defining Named Queries @Entity @NamedQueries( { @NamedQuery(name = "findAll", query="select c from Customer c"), @NamedQuery(name = "findVincent", query="select c from Customer c where c.firstName = 'Vincent'"), @NamedQuery(name = "findWithParam", query="select c from Customer c where c.firstName = :fname") }) public class Customer { @Id @GeneratedValue private Long id; private String firstName; /* etc. */ } Adapted from: Goncalves: Code and Models licensed under a CC BY-SA 3.0 License from https://github.com/agoncal/agoncal-book-javaee7
  • 33. Andreas Martin - Page 33 Hands-on 2 MANAGING PERSISTENT OBJECTS 3. Persistence Layer Based on: Goncalves, 2010: Beginning Java™ EE 6 Platform with GlassFish™ 3
  • 34. Andreas Martin - Page 34 Hands-on 2 1. Import the «hands-on-2» project. 2. Create the following entities: Address and Customer  Fields of Address: id, street1, city, zipcode und country.  Fields of Customer: id, firstName, lastName, email und address.  Please give the entities a unique table name. 3. Write a main method in a Main class and enter some data into the database. 3. Persistence Layer