Lecture 9 - Java Persistence, JPA 2

48
Java Persistence, JPA 2 Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE

Transcript of Lecture 9 - Java Persistence, JPA 2

Page 1: Lecture 9 - Java Persistence, JPA 2

Java Persistence, JPA 2

Fahad R. Golra

ECE Paris Ecole d'Ingénieurs - FRANCE

Page 2: Lecture 9 - Java Persistence, JPA 2

Lecture 8 - Java Persistence, JPA 2

• Introduction to Persistence • Entity Beans • Life cycle of Entity Beans • Associations • Entity Beans: Query Language

2 JEE - Java Persistence, JPA 2.x

Page 3: Lecture 9 - Java Persistence, JPA 2

Introduction to Entity Beans

• Entity Bean • Persistent objects stored in the database

• Persistence • by serialization • by object - relational database mapping

• Serialization • Saving the state of an object in the form of bytes • An object can be reconstructed once serialized • No complex queries, hard to maintain

3 JEE - Java Persistence, JPA 2.x

Page 4: Lecture 9 - Java Persistence, JPA 2

Persistence by mapping objects to relational databases

• State of the object is store in a database • For example: a book object has the attributes

names and isbn. We map them to a table which has two columns: name and isbn.

• Every object is decomposed into multiple variables, and their values are then stored in one or more tables.

• Allows complex queries

• SQL is hard to test/debug

4 JEE - Java Persistence, JPA 2.x

Page 5: Lecture 9 - Java Persistence, JPA 2

Persistence by mapping objects to relational databases

5

Page 6: Lecture 9 - Java Persistence, JPA 2

Object Databases

• Object databases (also known as object-oriented database management systems) can store the objects directly to databases.

• No mapping !!!

• Object Query Language (OQL) can be used to manipulate objects

• Easy to use, but not scalable.

6 JEE - Java Persistence, JPA 2.x

Page 7: Lecture 9 - Java Persistence, JPA 2

Persistence through JPA 2

• JPA 2 proposes a standard model of persistence through the use of Entity Beans

• Tools that ensure this persistence are integrated with the application servers and must be compatible to JPA 2 standard • e.g. Toplink, Hibernate, EclipseLink

• Java EE permits the use of dependency injection through annotations on all the layers.

7 JEE - Java Persistence, JPA 2.x

Page 8: Lecture 9 - Java Persistence, JPA 2

What is an Entity Bean?

• An object that is mapped to a database • It uses the persistence mechanisms

• It serves to represent the data placed in the database as objects • An object = one or more rows in one or more tables

in the database

• Example • A student entity is represented by a row of data in

student table of a database

8 JEE - Java Persistence, JPA 2.x

Page 9: Lecture 9 - Java Persistence, JPA 2

Why an Entity Bean?

• Easy to manipulate by programs • Instance of Account entity

• A compact view of grouped data in an object • Account object gives access to all public variables

• Associating methods to manipulate the data • methods can be written to add behavior to Account

• The data in the database will be updated automatically

• Instance of an entity bean is a view in memory of physical data

9 JEE - Java Persistence, JPA 2.x

Page 10: Lecture 9 - Java Persistence, JPA 2

Entity Bean

• Entity Bean is a POJO with attributes, getters & setters. • These attributes are mapped to database tables

• We use annotations to define the mapping to attributes • Primary Key, is a serializable object • Attributes of annotations to customize the mapping

10 JEE - Java Persistence, JPA 2.x

Page 11: Lecture 9 - Java Persistence, JPA 2

Persistent Fields and Properties

• Java primitive types

• java.lang.String

• Other serializable types, including:

• Wrappers of Java primitive types

• java.math.BigInteger

• java.math.BigDecimal

• java.util.Date

• java.util.Calendar

• java.sql.Date

• java.sql.Time

11

• java.sql.TimeStamp

• User-defined serializable types

• byte[]

• Byte[]

• char[]

• Character[]

• Enumerated types

• Other entities and/or collections of entities

• Embeddable classes

Page 12: Lecture 9 - Java Persistence, JPA 2

Example: Entity Bean (Book)

@Entitypublic class Book implements Serializable {

private static final long serialVersionUID = 1L;@Id@GeneratedValueprivate 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}

12

Page 13: Lecture 9 - Java Persistence, JPA 2

Example Entity Bean: Book

13 JEE - Java Persistence, JPA 2.x

Page 14: Lecture 9 - Java Persistence, JPA 2

Entity Manager

• We manipulate the data in the database with the help of Entity Beans and a Entity Manager

• Entity Manager is responsible of access the disks, caches, etc.

• Entity Manager controls when and how we can access the database.

• It generates the SQL.

14 JEE - Java Persistence, JPA 2.x

Page 15: Lecture 9 - Java Persistence, JPA 2

Example: Client (Inserting a Book)

public class BookHandler {public static void main(String[] args) {

Book book = new Book();book.setTitle("The Hitchhiker's Guide to the Galaxy");book.setPrice(12.5F);book.setDescription("Science fiction comedy book”);// set other fields as well . . . // Get a pointer to entity manager. We don't need to do this in web app!EntityManagerFactory emf = Persistence

.createEntityManagerFactory("chapter02PU");EntityManager em = emf.createEntityManager();

// Persisting the object in a transactionEntityTransaction tx = em.getTransaction();tx.begin();em.persist(book);tx.commit();

em.close();emf.close();

}}15

Page 16: Lecture 9 - Java Persistence, JPA 2

Session Bean as a Client

• In such a case • Dependency injection can be used • Transactions are started by default

@Stateless@LocalBeanpublic class MySessionBean {

EntityManager em;public Employee createEmployee(int id, String name, long salary) {

Employee emp = new Employee(id);emp.setName(name);…..em.persist(emp);return emp;

}}

16 JEE - Java Persistence, JPA 2.x

Page 17: Lecture 9 - Java Persistence, JPA 2

Session Bean as a Client

17

@Statelesspublic class BookBean {

@PersistenceContext(unitName = "bookLib")private EntityManager em;

public void createBook() {Book book = new Book();book.setId(1234L);book.setTitle("The Alpha Book");book.setPrice(13.5F);book.setDescription("Description of my book");book.setIsbn("1-465-65465");book.setNbOfPage(230);book.setIllustrations(false);

em.persist(book);

book = em.find(Book.class, 1234L);

System.out.println(book);}}

Page 18: Lecture 9 - Java Persistence, JPA 2

Why use session beans?

• They are used to implement the business logic

• A session bean can be used to implement Data Access Object (DAO) • DAO offers the functions of creation, searching,

modification and deletion of entity beans.

• Session beans can also be used to implement composite services.

18 JEE - Java Persistence, JPA 2.x

Page 19: Lecture 9 - Java Persistence, JPA 2

Other Annotations

@Entitypublic class Book implements Serializable {

@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;@Column(name = "book_title", nullable = false, updatable = false)private String title;private Float price;@Column(length = 2000)private String description;private String isbn;@Column(name = "nb_of_page", nullable = false)private Integer nbOfPage;@Basic(fetch = FetchType.LAZY)@Lobprivate Boolean illustrations;

// Constructors, getters, setters}

19

Page 20: Lecture 9 - Java Persistence, JPA 2

Other Annotations

• @Column • allows the preferences for columns • Attributes: name, unique, nullable, insertable,

updatable, length, ….

• @Generated Value • indicates the strategy for the automatic generation

of primary keys • It depends on the database being used, so

automatic is recommended

20 JEE - Java Persistence, JPA 2.x

Page 21: Lecture 9 - Java Persistence, JPA 2

Other Annotations

• @Lob • indicates “large object” for a BLOB • Often used with @Basic(fetch=FetchType.LAZY) for

indicating that we want this attribute to be loaded only when a get is used on it.

• There are many other annotations. • Java EE 7 specification can be consulted for it.

21 JEE - Java Persistence, JPA 2.x

Page 22: Lecture 9 - Java Persistence, JPA 2

Example: Persistence.xml

<?xml version="1.0" encoding="UTF-8"?><persistence 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_1_0.xsd" version="1.0">

<persistence-unit name="JPA_first"><provider>oracle.toplink.essentials.PersistenceProvider</provider><class>com.ece.jee.entities.Client</class>

<properties><property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver" /

><property name="toplink.jdbc.url" value="jdbc:mysql://localhost:

3306/ece_db" /><property name="toplink.jdbc.user" value="root" /><property name="toplink.jdbc.password" value="secret" /><property name="toplink.target-database" value="MySQL4" /><property name="toplink.ddl-generation" value="drop-and-create-

tables" /><property name="toplink.ddl-generation.output-mode" value="both" /><property name="toplink.logging.level" value="FINE" />

</properties></persistence-unit>

</persistence>22

Page 23: Lecture 9 - Java Persistence, JPA 2

Persistence Context

• A persistence context is a set of entity instances in which for every persistent entity identity there is a unique entity instance.

• The entity instances and their lifecycle are managed within the persistence context.

• The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary keys, and to query over entities.

23 JEE - Java Persistence, JPA 2.x

Page 24: Lecture 9 - Java Persistence, JPA 2

Life cycle of Entity Bean

24 JEE - Java Persistence, JPA 2.x

Page 25: Lecture 9 - Java Persistence, JPA 2

Life cycle of Entity Bean

• New: The bean exists in the memory but is not mapped to DB yet. It is not yet mapped to persistence context (via entity manager)

• Managed: The bean is mapped to the DB. The changes effect the data in DB.

• Detached: The bean is not mapped to the persistence context anymore.

• Removed: The bean is still mapped to the persistence context and the DB, but it is programmed to be deleted.

25 JEE - Java Persistence, JPA 2.x

Page 26: Lecture 9 - Java Persistence, JPA 2

Life cycle of Entity Bean

• remove(): To delete the data

• set(), get(): If the bean is in managed state, these methods (of the entity bean) are used to access or modify the data.

• persist(): To create the data. The bean goes to managed state.

• merge(): To take a bean from detached state to a managed state.

26 JEE - Java Persistence, JPA 2.x

Page 27: Lecture 9 - Java Persistence, JPA 2

Entity Manager example methods

public Account openAccount(String ownerName) {Account account = new Account();account.ownerNamer = ownerName;em.persist(account); // attach the bean & persistreturn account; // copy is detached

}

public void update(Account detachedAccount) {Account managedAccount = em.merge(detachedAccount);

}

public void delete(Account detachedAccount) {Account managedAccount = em.merge(detachedAccount);em.remove(managedAccount);

}

public void findAccount(int id) {return em.find(Account.class, Integer.valueOf(id));

}

27

Page 28: Lecture 9 - Java Persistence, JPA 2

Entity Manager (other principal methods)

Object find(Class cl, Object key) : • Find an EntityBean by its id

boolean contains(Object entity) : • True if the entity is attached to the EntityManager

Query createQuery(String sqlString) : • Creating a query in EJB-QL

Query createNamedQuery(String name) : • Creating a named query

Query createNativeQuery(String sqlQuery) : • Creating an SQL query

void refresh(Object entity) : • Recharging the bean from the DB

28 JEE - Java Persistence, JPA 2.x

Page 29: Lecture 9 - Java Persistence, JPA 2

Using composite columns

• Fields of two classes into one table

@Embeddablepublic class Address {

private String street;private int postalCode;

}

@Entitypublic class User {

private String name;@Embeddedprivate Address address;

}

29

Page 30: Lecture 9 - Java Persistence, JPA 2

Composite Primary Key

• Instead of using @Embedded we use @EmbeddedId for composite primary keys

@Embeddablepublic class CompositeId {

private String name;private String email;

}

@Entitypublic class Dependent {

@EmbeddedIdCompositeId id;@ManyToOneEmployee emp;

}

30

Page 31: Lecture 9 - Java Persistence, JPA 2

Associations

• Cardinality • 1 - 1 (one to one): one employee has one address • 1 - n (one to many): one employee has multiple addresses • n - 1 (many to one): multiple employees have one address • n - n (many to many): multiple employees have multiple

addresses

• Direction (navigability) • Unidirectional:

• we can go from bean A to bean B only • Bi-directional:

• we can go from bean A to bean B & vice-versa

31 JEE - Java Persistence, JPA 2.x

Page 32: Lecture 9 - Java Persistence, JPA 2

Unidirectional: OneToOne

• Employee entity -> ︎Employee table

• Address entity -> ︎Address table with address_Id as PK • Employee table owns a foreign key to Address, address

@Entitypublic class Employee {

private Address address;@OneToOnepublic Address getAddress() {

return address;}public void setAddress(Address ad) {

this.address = ad;}

}

32

@Entitypublic class Address {…}

Employee Address1 1

adress

Page 33: Lecture 9 - Java Persistence, JPA 2

Unidirectional: ManyToOne

• Employee entity -> ︎Employee table

• Address entity -> ︎Address table with address_Id as PK • Employee table owns a foreign key to Address, address

@Entitypublic class Employee {

private Address address;@ManyToOnepublic Address getAddress() {

return address;}public void setAddress(Address ad) {

this.address = ad;}

}

33

@Entitypublic class Address {…}

Employee Address0..* 1

adress

Page 34: Lecture 9 - Java Persistence, JPA 2

Unidirectional: OneToMany

• Employee entity -> ︎Employee table

• Address entity -> ︎Address table with address_Id as PK • Creation of a join table Employee_Address with two columns (i.e.

Employee_Pkemployee & Address_PKAddress, each column represents a PK to each table

@Entitypublic class Employee {

private Collection<Address> addresses;@OneToManypublic Collection<Address> getAddresses() {

return addresses;}public void setAddresses(Collection<Address> addresses) {

this.addresses = addresses;}

}34

@Entitypublic class Address {…}

Employee Address1 0..*

adresses

Page 35: Lecture 9 - Java Persistence, JPA 2

Unidirectional: ManyToMany

• Employee entity -> ︎Employee table

• Address entity -> ︎Address table with address_Id as PK • Creation of a join table Employee_Address with two columns (i.e.

Employee_Pkemployee & Address_PKAddress, each column represents a PK to each table

@Entitypublic class Employee {

private Collection<Address> addresses;@ManyToManypublic Collection<Address> getAddresses() {

return addresses;}public void setAddresses(Collection<Address> addresses) {

this.addresses = addresses;}

}35

@Entitypublic class Address {…}

Employee Address0..* 0..*

adresses

Page 36: Lecture 9 - Java Persistence, JPA 2

Bi-directional: OneToOne

• Employee entity -> ︎Employee table

• Cashier entity -> ︎Cashier table with myCashier_Id as PK • Employee table owns a foreign key to Cashier, myCashier

(note: Cashier will not have a foreign key to Employee)

36

@Entitypublic class Cashier {

private Employee myEmployee;@OneToOne(mappedBy = "myCashier")public Employee getMyEmployee() {

return myEmployee;}public void setMyEmploye(Employee e) {

this.myEmployee = e;}

}

@Entitypublic class Employee {

private Cashier myCashier;@OneToOnepublic Cashier getMyCashier() {

return myCashier;}public void setMyCashier(Cashier c) {

this.myCashier = c;}

}

Employee Cashier1 1

myCashiermyEmployee

Page 37: Lecture 9 - Java Persistence, JPA 2

Bi-directional: ManyToOne/OneToMany

• Employee entity -> ︎Employee table

• Cashier entity -> ︎Cashier table with myCashier_Id as PK • Employee table owns a foreign key to Cashier, myCashier

(note: Cashier will not have a foreign key to Employee)

37

@Entitypublic class Cashier {

private Collection<Employee> myEmployees;@OneToMany(mappedBy = "myCashier")public Collection<Employee>

getMyEmployees() {return myEmployees;

}public void

setMyEmployees(Collection<Employee> e) {this.myEmployees = e;

}}

@Entitypublic class Employee {

private Cashier myCashier;@ManyToOnepublic Cashier getMyCashier() {

return myCashier;}public void setMyCashier(Cashier c) {

this.myCashier = c;}

}

Employee Cashier0..* 1

myCashiermyEmployees

Page 38: Lecture 9 - Java Persistence, JPA 2

Bi-directional: ManyToMany

• Employee entity -> ︎Employee table

• Cashier entity -> ︎Cashier table

• Creation of a join table Project_Employee with two columns (i.e. myProjects_PKProject & myEmployees_PkEmployee, each column represents a PK to each table

38

@Entitypublic class Employee {

private Collection<Project> myProjects;@ManyToMany(mappedBy = "myEmployees")public Collection<Project> getMyProjets()

{return myProjects;

}public void

setMyProjets(Collection<Project> p) {this.myProjects = p;

}}

@Entitypublic class Project {

Collection<Employee> myEmployees;@ManyToManypublic Collection<Employee>

getMesEmployees() {return myEmployees;

}public void

setMesEmployes(Collection<Employee> e) {this.myEmployees = e;

}}

Project Employee0..* 0..*

myEmployeesmyProjects

Page 39: Lecture 9 - Java Persistence, JPA 2

Entity Bean Inheritance

• Entities support inheritance and polymorphism

• Entities may be concrete or abstract @Entitypublic abstract class Person {@Idprotected String name; …

}

@Entitypublic class Employee extends Person {protected float salary; …

}

39 JEE - Java Persistence, JPA 2.x

Page 40: Lecture 9 - Java Persistence, JPA 2

Inheritance Strategies

• One Table by classes hierarchy (Default) : @Inheritance(strategy=SINGLE_TABLE)

• Implemented in most tooling solutions • Good support of polymorphism • Columns proper to sub-classes set at null

• One Table by concrete class: @Inheritance(strategy=TABLE_PER_CLASS)

• Some issues remain regarding polymorphism • Join Strategy: • @Inheritance(strategy=JOINED)

• a join between the concrete class and the super class tables • Good support of polymorphism • Not always implemented • Join operation can be costly

40 JEE - Java Persistence, JPA 2.x

Page 41: Lecture 9 - Java Persistence, JPA 2

Entity Bean Inheritance

• An Entity can inherit a non-entity class and vice-versa • MappedSuperClasses are not accessible to EntityManager

• Not considered as Entity (no table in DB) @MappedSuperclasspublic abstract class Person {

protected Date dob;}

@Entitypublic class Employee extends Person {

@Idprotected int id;protected String name;

}

41 JEE - Java Persistence, JPA 2.x

Page 42: Lecture 9 - Java Persistence, JPA 2

Entity Bean Compliments

• Fetch: option for loading the graph of objects • FetchType.EAGER : loads all the tree (required if Serializable) ︎ • FetchType.LAZY : only on demand (unusable with Serializable)

• Cascade: transitivity of operations over the beans • CascadeType.ALL: every operation is propagated • CascadeType.MERGE: in case of a merge • CascadeType.PERSIST: When film Entity becomes

persistent, then List<Cinema> too • CascadeType.REFRESH: loading from the DB • ︎CascadeType.REMOVE: delete in cascade

42 JEE - Java Persistence, JPA 2.x

Page 43: Lecture 9 - Java Persistence, JPA 2

Entity Beans: Query Language

• parameters indicated by :param-name • Request in Query object • Result from Query object

• getResultList() • getSingleResult()

43 JEE - Java Persistence, JPA 2.x

Page 44: Lecture 9 - Java Persistence, JPA 2

Entity Beans: Named Query

• Named query can be attached to the Entity Bean

44 JEE - Java Persistence, JPA 2.x

Page 45: Lecture 9 - Java Persistence, JPA 2

Entity Beans: Native Query

• SQL queries can be used using • createNativeQuery(String sqlString) • createNativeQuery(String sqlString, Class resultClass)

45 JEE - Java Persistence, JPA 2.x

Page 46: Lecture 9 - Java Persistence, JPA 2

Entity Beans: Life cycle interceptors

• Interception of state changes

• Around the creation (em.persist) : ︎ • @PrePersist • @PostPersist

• At loading time from DB (em.find, Query.getResultList) • @PostLoad

• Around updates (modification of a field, em.merge) ︎ • @PreUpdate • @PostUpdate

• Around a remove action (em.remove) ︎ • @PreRemove • @PostRemove

46

Page 47: Lecture 9 - Java Persistence, JPA 2

References

• Some of the slide contents are take from the slides of • Reda Bendraou, UPMC • Michel Buffa, UNSA

47 JEE - Java Persistence, JPA 2.x

Page 48: Lecture 9 - Java Persistence, JPA 2

48 JEE - Java Persistence, JPA 2.x