PR3_Ch05_Java_Persistence_API_(JPA) PDF
Document Details
Uploaded by WellMadeSerpentine1417
Islamic University of Gaza
2025
Dr. Abdelkareem Alashqar
Tags
Related
- Java Persistence with Spring Data and Hibernate (Catalin Tudose) (Z-Library).pdf
- Java Persistence with Spring Data and Hibernate (Catalin Tudose) (Z-Library).pdf
- Persistence with Spring PDF
- Chapitre 8 - Entreprise Java Bean (EJB3 Entity) PDF
- Enterprise Application Programming PDF
- CS27020 Object Relational Mapping and a Persistence Layer PDF
Summary
This document is a lecture presentation on Java Persistence API (JPA). It covers topics including introduction to Java persistence, Object Relational Mismatch, JPA Architecture, Annotations, Entities, EntityManager & the Persistent Context, Persistence Units, Exceptions, JPA Query Language (JPQL).
Full Transcript
Programming 3 CSCI 2308 Chapter 5 Java Persistence API (JPA) Topics Covered Introduction to java persistence Object Relational Mismatch The Java Persistence API (JPA) JPA Architecture Annotations Entities En...
Programming 3 CSCI 2308 Chapter 5 Java Persistence API (JPA) Topics Covered Introduction to java persistence Object Relational Mismatch The Java Persistence API (JPA) JPA Architecture Annotations Entities EntityManager & the Persistent Context Persistence Units Exceptions JPA Query Language (JPQL) Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 2 Introduction Java programmers use lots of code to interact with the database. In JDBC, we "hard coded" SQL into our application Using Java Persistence API (JPA), the load of interacting with the database reduces significantly. JPA provides a technique for bridging the gap between the object model and relational model. This technique is known as Object Relational Mapping (ORM). Mapping from tabular format to object format Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 3 Storing/Retrieving Object From a Relational DB Java Class Database table public class Employee { private int id; employee private String name; id name dept salary private String dept; private double salary; public Employee() { } //setters and getters... } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 4 Object Relational Mismatch SQL Types and Java Types are different Databases also support SQL types differently Tend to define their own internal data types (e.g. NUMBER type in Oracle) Types must be mapped between Java and SQL/Database JDBC (Generic SQL) Types are defined in java.sql.Types Java types are very rich but SQL types are more restrictive Important issues: Map class to table 1:1 and 1:n Map columns to class properties Supporting BLOB, Streaming, etc. Object Oriented design issues like inheritance, abstraction, and reuse Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 5 What is JPA? JPA is a collection of classes and methods to persistently store the large amount of data into a database. JPA was first released as a subset of the EJB 3.0 specification in Java EE5. Then evolved starting with the release of JPA 2.0 in Java EE6. Currently, JPA 2.2 has been adopted for continuation as part of Jakarta EE. JPA is an open source API, so vendors/individuals provide new products for implementing and enhancing JPA persistence. Products include: Hibernate, Eclipselink, Toplink, Spring Data JPA, etc. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 6 Java Persistence Java Persistence consists of three areas: The Java Persistence API The query language Object/relational mapping metadata Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 7 JPA Architecture Java Application Query EntityManagerFactory Entity EntityManager EntityTransaction JPA provider JDBC driver Persistence DB Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 8 JPA Classes in javax.persistence Package Units Description EntityManagerFactory This is a factory class of EntityManager. It creates and manages multiple EntityManager instances. EntityManager It is an Interface, it manages the persistence operations on objects. It works like factory for Query instance. Entity Entities are the persistence objects, stored as records in the database. EntityTransaction It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class. Persistence This class contain static methods to obtain EntityManagerFactory instance. Query This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 9 Annotations Annotations start with '@' symbol. Annotations are declared prior to a class, property, or method. All annotations of JPA are defined in the javax.persistence package. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 10 Some Annotations Provided by javax.persistence Package Annotation Description @Entity Declares the class as an entity or a table. @Table Declares table name. @Basic Specifies non-constraint fields explicitly. @Embedded Specifies the properties of class or an entity whose value is an instance of an embeddable class. @Id Specifies the property, use for identity (primary key of a table) of the class. @GeneratedValue Specifies how the identity attribute can be initialized such as automatic, manual, or value taken from a sequence table. @Transient Specifies the property that is not persistent, i.e., the value is never stored in the database. @Column Specifies the column attribute for the persistence property. @SequenceGenerator Specifies the value generator for the property that is specified in the @GeneratedValue annotation. It creates a sequence. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 11 Some Annotations Provided by javax.persistence Package (cont.) Annotation Description @TableGenerator Specifies the value generator for the property specified in the @GeneratedValue annotation. It creates a table for value generation. @JoinColumn Specifies an entity association or entity collection. This is used in many- to-one and one-to-many associations. @UniqueConstraint Specifies the fields and the unique constraints for the table. @ManyToMany Defines a many-to-many relationship between the join Tables. @ManyToOne Defines a many-to-one relationship between the join Tables. @OneToMany Defines a one-to-many relationship between the join Tables. @OneToOne Defines a one-to-one relationship between the join Tables. @NamedQueries Specifies list of named queries. @NamedQuery Specifies a Query using static name. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 12 Entities An entity is a Plain Old Java Object (POJO) The Class represents a table in a relational database. Instances correspond to rows Requirements for entities: Annotated with the annotation @Entity. public or protected, No-argument constructor (May have additional constructors) The class must Not be declared final No methods or persistent instance variables must be declared final Continued … Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 13 Entities (cont.) … May be Serializable, but not required ̶ Only needed if passed by value (in a remote call) Entities may extend both entity and non-entity classes Non-entity classes may extend entity classes Persistent instance variables must be declared private, protected, or package-private Example: @Entity class Employee{... } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 14 Persistent Fields and Properties The persistent state of an entity can be accessed: Through the entity’s instance variables Through JavaBeans-style properties (getters/setters) Supported types: Primitive types, String, other serializable types, enumerated types Other entities and/or collections of entities Embeddable classes All fields not annotated with @Transient or not marked as Java transient will be persisted to the data store. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 15 Primary Keys in Entities Each entity must have a unique object identifier (persistent identifier) @Entity public class Employee { @Id private int id; Primary key private String name; private double salary; public int getId() { return id; } public void setId(int id) { this.id = id; }... } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 16 Persistent Identity Identifier (id) in entity represents a primary key (PK) in database Uniquely identifies entity in memory and in DB Persistent identity types: Simple id – single field/property @Id int id; Compound id – multiple fields/properties @Id int id; @Id String name; Embedded id – single field of PK class type @EmbeddedId EmployeePK id; Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 17 Identifier Generation Identifiers can be generated in the database by specifying @GeneratedValue on the identifier Four pre-defined generation strategies: AUTO, IDENTITY, SEQUENCE, TABLE Generators may pre-exist or be generated Specifying strategy of AUTO indicates that the provider will choose a strategy @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; The selection of generation strategy depends on database (such as MySQL, Oracle) Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 18 Customizing the Entity Object In most of the cases, the defaults are sufficient By default the table name corresponds to the unqualified name of the class Customization: @Entity @Table(name = "EMPLOYEE_TABLE") public class Employee{... } The defaults of columns can be customized using the @Column annotation @Id @Column(name = "EMPLOYEE_ID", nullable = false) private int id; @Column(name= "EMPLOYEE_NAME" nullable= true, length= 100) private String name; Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 19 Entity Relationships There are four types of relationship multiplicities: @OneToOne @OneToMany @ManyToOne @ManyToMany The direction of a relationship can be: Bidirectional: owning side and inverse (referencing) side Unidirectional : owning side only Owning side specifies the physical mapping Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 20 ManyToOne Mapping @Entity public class Employee { employee @Id id name salary dept_id int id;... @ManyToOne @JoinColumn(name = "dept_id") Department dept; } department id name location @Entity public class Department { @Id int id;... Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 21 OneToMany Mapping @Entity public class Department { department @Id id name location int id;... @OneToMany(mappedBy="dept") List employees; //collection is needed } employee @Entity id name salary dept_id public class Employee { @Id int id;... @ManyToOne Department dept; } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 22 ManyToMany Mapping @Entity public class Employee { employee @ID int id; id name salary dept_id... @JoinTable( name="employee_project", joinColumns=@JoinColumn(name="employee_id"), inverseJoinColumns=@JoinColumn(name="project_id") List projects; //collection is needed } employee_project employee_id project_id @Entity public class Project { project @ID int id; id name location... @ManyToMany(mappedBy="projects") List employees; //collection is needed } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 23 Entity Relation Attributes JPA supports cascading updates/deletes CascadeType ̶ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH You can declare performance strategy to use with fetching related rows FetchType ̶LAZY, EAGER ̶Lazy means don't load row until the property is retrieved @ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER) Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 24 Entity Inheritance An important capability of the JPA is its support for inheritance and polymorphism Entities can inherit from other entities and from non- entities The @Inheritance annotation identifies a mapping strategy: SINGLE_TABLE JOINED TABLE_PER_CLASS Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 25 Inheritance Example @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="DISC", discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue(name="EMPLOYEE") public class Employee {... } @Entity @DiscriminatorValue(name="SEMPLOYEE") public class SalariedEmployee extends Employee {... } SINGLE_TABLE strategy: all classes in the hierarchy are mapped to a single table in the DB Discriminator column: contains a value that identifies the subclass Discriminator type: {STRING, CHAR, INTEGER} Discriminator value: value entered into the discriminator column for each entity in a class hierarchy Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 26 Managing Entities Entities are managed by the entity manager The entity manager is represented by javax.persistence.EntityManager instances Each EntityManager instance is associated with a persistence context A persistence context defines the scope under which particular entity instances are created, persisted, and removed Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 27 Persistence Context A persistence context is a set of managed entity instances that exist in a particular data store Entities keyed by their persistent identity Only one entity with a given persistent identity may exist in the persistence context Entities are added to the persistence context, but are not individually removable ("detached") Controlled and managed by EntityManager Contents of persistence context change as a result of operations on EntityManager API Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 28 Persistence Context Application Persistence Context EntityManager MyEntity A MyEntity C MyEntity a MyEntity B MyEntity b Entities Entity state DB Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 29 Entity Manager An EntityManager instance is used to manage the state and life cycle of entities within a persistence context Entities can be in one of new new() persist() the following states: refresh() 1. New managed remove() 2. Managed retrieve persist() removed 3. Detached merge() end of context 4. Removed DB flush/commit detached Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 30 Entity Lifecycle New: entity is instantiated but not associated with persistence context. Not linked to database. Managed: associated with persistence context. Changes get synchronized with database Detached: has an id, but not connected to database Removed: associated with persistence context, but underlying row will be deleted. The state of persistent entities is synchronized to the database when the transaction commits Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 31 Entity Manager The EntityManager API: creates and removes persistent entity instances finds entities by the entity’s primary key allows queries to be run on entities Java SE applications create EntityManager instances by using directly Persistence and EntityManagerFactory: javax.persistence.Persistence ̶ Root class for obtaining an EntityManager ̶ Locates provider service for a named persistence unit ̶ Invokes on the provider to obtain an EntityManagerFactory javax.persistence.EntityManagerFactory ̶ Creates EntityManagers for a named persistence unit or configuration Applications must manage own transactions too. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 32 EntityManager in Java Application public class PersistenceProgram { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("SomePUnit"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // Perform finds, execute queries,... // update entities, etc. em.getTransaction().commit(); em.close(); emf.close(); } } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 33 JPA Transaction Example public class PersistenceProgram { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("CompanyPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Department department = new Department("Marketing","Gaza"); em.persist(department); Employee employee= new Employee("Ali", 1001.2, department); em.persist(employee); employee = new Employee("Huda", 1210.5, department); em.persist(employee); em.getTransaction().commit(); em.close(); emf.close(); } } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 34 Transactions JPA transactions can be managed by: A Java SE users application ̶Called application-managed entity manager ̶Using EntityTransaction API (tx.begin(), tx.commit(), etc.) A Java EE container (such as Tomcat server) ̶Called container-managed entity manager A framework (such as Spring Boot) Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 35 Operations on Entity Objects EntityManager API operations: persist()- Save the entity into the database remove()- Delete the entity from the database refresh()- Reload the entity state from the database merge()- Synchronize a detached entity with the current persistence context find()- Find by primary key createQuery()- Create query using dynamic JPQL createNamedQuery()- Create a predefined query createNativeQuery()- Create a native "pure" SQL query. Can also call stored procedures. contains()- Is entity is managed by current persistence context flush()- Force synchronization of current persistence context to database Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 36 Persistence Units A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application Each persistence unit can have different providers and database drivers Persistence units are defined by the persistence.xml configuration file Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 37 persistence.xml org.eclipse.persistence.jpa.PersistenceProvider javajpaapp2.Employee javajpaapp2.Department