Architecture Entity Beans Java Persistence API

26
Architecture Entity Beans Java Persistence API [email protected] www.ericgerlofsma.nl

description

Architecture Entity Beans Java Persistence API. [email protected] www.ericgerlofsma.nl. JPA ?. This new API simplifies the development of Java EE and Java SE applications using data persistence. The Java Persistence API is a POJO persistence API for object/relational mapping. - PowerPoint PPT Presentation

Transcript of Architecture Entity Beans Java Persistence API

Page 1: Architecture Entity Beans Java Persistence API

Architecture Entity BeansJava Persistence API

[email protected]

www.ericgerlofsma.nl

Page 2: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

JPA ?• This new API simplifies the development of Java EE and Java SE

applications using data persistence.

• The Java Persistence API is a POJO persistence API for object/relational mapping.

• It supports the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database.

• You can obtain the open source GlassFish project implementation of the Java Persistence API for stand-alone applications..

Page 3: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

New Style• Next example will show you,

• the difference between old style database access,

• and new JPA style database access.

Page 4: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

META-INF/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="CIJFERLIJST"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <class>efg.rmi.server.Student</class> <properties> <property name="toplink.target-database"

value="oracle.toplink.essentials.platform.database.AccessPlatform"/> <property name="toplink.jdbc.driver" value="sun.jdbc.odbc.JdbcOdbcDriver"/> <property name="toplink.jdbc.user" value="efg"/> <property name="toplink.jdbc.password" value="geheim"/> <property name="toplink.jdbc.url" value="jdbc:odbc:CIJFERLIJST"/> </properties> </persistence-unit> </persistence>

You need a driver to a database !

Page 5: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

POJO Entity BeanImport ...

@Entity@Table( name = CijferlijstImpl.tablename )public class Student implements Serializable{ private String name = null; private String cijfer = null; public Student() {} public Student(String newName, String newCijfer) { name = newName; cijfer = newCijfer; } @Id @Column( name = "S_Name" ) public String getName() { return name; } public void setName(String newName) { name = newName; } @Column( name = "S_Cijfer" ) public String getCijfer() { return cijfer; } public void setCijfer(String newCijfer) { cijfer = newCijfer; }}

You need a POJO mapping to a database table-entry!

Page 6: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Entity Managerpublic void update(String name, String newName, String newCijfer){ EntityManagerFactory entityManagerFactory =

Persistence.createEntityManagerFactory("CIJFERLIJST"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); Student student = entityManager.find(Student.class, name); student.setName(newName); student.setCijfer(newCijfer); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close();}

You need a database connection !

This is a stand-alone example!

Page 7: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

JPA

CijferlijstApplication

StudentJava-bean

EntityManager

Database

database wrapper

Page 8: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Java Bean uses 4 annotations• @Entity ( For defining an Entity Bean)

• @Table ( For defining the table name )

• @Id ( For defining the primary key )

• @Column ( For defining the column name )

• There are 64 annotations more in JPA!

Page 9: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.Entity@Target(value=TYPE) @Retention(value=RUNTIME) public @interface Entity{ String name; }

The optional name of an entity. Defaults to the unqualified name of the entity class. This name is used to refer to the entity in queries. The name must not be a reserved literal in the Java Persistence query language.

Page 10: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.Table@Target(value=TYPE)@Retention(value=RUNTIME) public @interface Table{ String catalog; // The catalog of the table String name; // The name of the table String schema; // The schema of the table UniqueConstraints[] uniqueConstraints; // Unique constraints that are to be placed on

the table}

This annotation specifies the primary table for the annotated entity. Additional tables may be specified using SecondaryTable or SecondaryTables annotation. If no Table annotation is specified for an entity class, the default values apply.

Page 11: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.UniqueConstraint

@Target(value={}) @Retention(value=RUNTIME) public @interface UniqueConstraint{ String[] columnNames;}

Required Element           An array of the column names that make up the constraint.

Page 12: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.Id@Target(value={METHOD,FIELD})

@Retention(value=RUNTIME)

public @interface Id

Specifies the primary key property or field of an entity.

Page 13: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.Column@Target(value={METHOD,FIELD})

@Retention(value=RUNTIME)

public @interface Column

String columnDefinition;

boolean insertable;

int length;

String name;

boolean nullable;

int precision;

int scale;

String table;

boolean unique;

boolean updatable

}

Is used to specify a mapped column for a persistent property or field.

If no Column annotation is specified, the default values are applied.

Page 14: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Entity Manager• javax.persistence.Persistence

BootStrap class that is used to obtain an EntityManagerFactory

• javax.persistence.EntityManagerFactoryThe EntityManagerFactory interface is used by the application to obtain an application-managed entity manager. When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.

• javax.persistence.EntityManagerInterface used to interact with the persistence context.An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. This interface defines the methods that are used to interact with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.

Page 15: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Entity Manager Methods• void clear()• void close()• boolean contains(Object entity)• Query createNamedQuery(String name)• Query createNativeQuery(...)• Query createQuery(String qlString)• <T> T find(Class<T> entityClass, Object primaryKey)• void flush()• Object getDelegate()• FlushModeType getFlushMode()• <T> T getReference(Class<T> entityClass, Object primaryKey)• EntityTransaction getTransaction()• boolean isOpen()• void joinTransaction()• void lock(Object entity, LockModeType lockMode)• <T> T merge(T entity)• void persist(Object entity)• void refresh(Object Entity)• void remove(Object Entity)• void setFlushMode(FlushModeType flushMode)

Red methods reflect the LifecycleBlue refers to Identity ManagementGreen refers to Cache Management

Page 16: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Entity Transaction Methods• void begin()• void commit()• boolean getRollbackOnly()• boolean isActive()• void rollback()• void setRollbackOnly()

Red methods reflect the Lifecycle

Page 17: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Entity Lifecycle Management

uit: http://docs.solarmetric.com/full/html/ejb3_overview_em_lifecycle.html http://java.boot.by/scbcd5-guide/ch06.html

Page 18: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Seven Relationship Types

1. One-to-one unidirectional2. One-to-one bidirectional

3. One-to-many unidirectional4. One-to-many bidirectional5. Many-to-one unidirectional6. Many-to-one bidirectional

7. Many-to many bidirectional

Page 19: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Example ABC-Library Bookpackage efg.library;

import . . . @Entity@Table(name = "books", schema = "library")

public class Book implements Serializable{ private String title = ""; private Customer lendTo = null; @Id @Column(name = "book_title") public String getTitle() { return title; } public void setTitle(String newTitle) { title = newTitle; } @ManyToOne @JoinColumn(name = "book_lendTo") public Customer getLendTo() { return lendTo; } public void setLendTo(Customer customer){ lendTo = customer; }

}

Page 20: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Example ABC-Library Customerpackage efg.library;

import . . . @Entity@Table(name = "customers", schema = "library")

public class Customer implements Serializable{ private String name = ""; private int credits = 0; private Collection<Book> books = null; @Id @Column(name = "customer_name") public String getName(){ return name; } public void setName(String newName){ name = newName; }

@Column(name = "customer_credits") public int getCredits(){ return credits; } public void setCredits(int newCredits){ credits = newCredits; } @OneToMany(mappedBy = "lendTo") public Collection<Book> getBooks(){ return books; } public void setBooks(Collection<Book> newBooks){ books = newBooks; }

}

Page 21: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

relationshipsBook

title: StringlendTo: Customer

Customer

name: Stringcredits: intbooks: Collection

1n

@ManyToOne@JoinColumn( name = "Book_LendTo" )public Customer getLendTo(){ return lendTo;}

@OneToMany( mappedBy = "lendTo" )public Collection<Book> getBooks(){ return books;}

Page 22: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Annotations• @ManyToOne

– This annotation defines a single-valued association to another entity class that has many-to-one multiplicity

• @OneToMany – Defines a many-valued association with one-to-many multiplicity

Page 23: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.OneToMany@Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface OneToMany{ String mappedBy; CascadeType[] cascade; FetchType fetch; Class targetEntity;}

If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified.

Enum CascadeType = { ALL, MERGE, PERSIST, REFRESH, REMOVE }Enum FetchType = { EAGER, LAZY }

Page 24: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

javax.persistence.ManyToOne@Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface ManyToOne{ boolean optional; CascadeType[] cascade; FetchType fetch; Class targetEntity;}

It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced

Page 25: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

Obtaining an EntityManager

An EntityManager should be injected directly into an EJB using the @javax.persistence.PersistenceContext annotation.

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

Page 26: Architecture Entity Beans Java Persistence API

04/22/23 www.ericgerlofsma.nl

META-INF/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="LIBRARY"> <jta-data-source>java:/DefaultDS</jta-data-source> <class>efg.library.entity.Book</class> <class>efg.library.entity.Customer</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> </properties> </persistence-unit>

</persistence>

updatecreate

or

org.hibernate.dialect.MySQLDialectorg.hibernate.dialect.Oracle9Dialet...

or