[go: up one dir, main page]

0% found this document useful (0 votes)
48 views106 pages

AJP - Unit 5

The document outlines the curriculum for an Advanced Java Programming course at the Noida Institute of Engineering and Technology, focusing on Java Persistence API (JPA). It includes faculty details, evaluation schemes, syllabus, course objectives, and outcomes, along with a comprehensive overview of JPA, its features, and ORM tools. Additionally, it provides quizzes and answers related to JPA concepts to assess student understanding.

Uploaded by

Aditya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views106 pages

AJP - Unit 5

The document outlines the curriculum for an Advanced Java Programming course at the Noida Institute of Engineering and Technology, focusing on Java Persistence API (JPA). It includes faculty details, evaluation schemes, syllabus, course objectives, and outcomes, along with a comprehensive overview of JPA, its features, and ORM tools. Additionally, it provides quizzes and answers related to JPA concepts to assess student understanding.

Uploaded by

Aditya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 106

Noida Institute of Engineering and Technology, Greater Noida

(Java Persistence API)JPA

Unit: 5

ADVANCED JAVA PROGRAMMING


(ACSE-0601)
Shweta Singh
Assistant Professor
Course Details
(B.Tech 6th Sem /3rd Year) CSE(AI)

Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 Unit-5


1
05/15/2025
Faculty Introduction
Name Shweta Singh
Qualification M. Tech. (CSE),Pursuing Ph.d(Engineering)
Designation Assistant Professor
Department Computer Science & Engineering-AI
Total Experience 13 years
NIET Experience 1 years
Subject Taught Core Java and Advance Java , BDA using Excel, Artificial
Intelligence, Soft Computing, C Programming, Web Technology,
Discrete Mathematics,Operating System,OOPs ,C++,Computer
Graphics.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 2


Unit-5
Table of Contents

1. Name of Subject with code, Course and Subject Teacher


2. Brief Introduction of Faculty member with Photograph
3. Evaluation Scheme
4. Subject Syllabus
5. Branch-wise Applications
6. Course Objective (Point wise)
7. Course Outcomes (COs)
8. Program Outcomes only heading (POs)
9. COs and POs Mapping
10.Program Specific Outcomes (PSOs)

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 3


Unit-5
Evaluation Scheme

Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 Unit-5


05/15/2025 4
Syllabus

Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 Unit-5


05/15/2025 5
Text Books

Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 Unit-5


05/15/2025 6
Branch Wise Application

1. Desktop GUI Applications


2. Mobile Applications
3. Enterprise Applications
4. Scientific Applications
5. Web-based Applications
6. Distributed Applications
7. Cloud-based Applications
8. Web servers and Application servers
9. Software Tools
10.Gaming Applications

Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 Unit-5


05/15/2025 7
End Semester Question Paper Templates (Offline Pattern/Online Pattern)

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 8


Unit-5
End Semester Question Paper Template

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 9


Unit-5
End Semester Question Paper Template

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 10


Unit-5
End Semester Question Paper Template

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 11


Unit-5
End Semester Question Paper Template

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 12


Unit-5
End Semester Question Paper Template

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 13


Unit-5
End Semester Question Paper Template

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 14


Unit-5
Prerequisite/Recap

• Student must know at least the basics of how to use a computer, and should be
able to start a command line shell.

• Knowledge of basic programming concepts, as covered in ‘Programming Basic'


course is necessary.

• Students must have basic understanding of computer programming and related


programming paradigms

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 15


Unit-5
About the Subject with videos
• In advanced java is to design console based, GUI based ,web based
applications, integrated development environment to create, debug and run
multi-tier and enterprise-level applications.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 16


Unit-5
Topic Objectives

After you have read and studied this topic, you should be able to

• To learn the JPA Concepts in Java.

• To learn the concept of ORM tools.

• To Understand the features entity and relation with object.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 17


Unit-5
Topic mapping with CO
Topic CO
overview of data persistence CO5

Overview of ORM tools CO5

Understanding JPA CO5

Entities CO5

Requirement for Entity Class CO5

Persistent Fields and Properties CO5

Primary keys in Entries CO5

Entity Management CO5

Entities Relationships. CO5

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 18


Unit-5
Introduction & overview of data persistence

• JPA is used to persist data between Java object and relational database.

• JPA acts as a bridge between object-oriented domain models and relational


database systems.

• As JPA is just a specification, it doesn't perform any operation by itself.

• It requires an implementation.

• So, ORM tools like Hibernate, TopLink and iBatis implements JPA specifications for
data persistence.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 19


Unit-5
JPA Versions
• The first version of Java Persistenece API,
• JPA 1.0 was released in 2006 as a part of EJB 3.0 specification.
• Following are the other development versions released under JPA specification:
• JPA 2.0 - This version was released in the last of 2009. Following are the important
features of this version: -
• It supports validation.
• It expands the functionality of object-relational mapping.
• It shares the object of cache support.
• JPA 2.1 - The JPA 2.1 was released in 2013 with the following features: -
• It allows fetching of objects.
• It provides support for criteria update/delete.
• It generates schema.
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 20
Unit-5
• JPA 2.2 - The JPA 2.2 was released as a development of maintainenece in 2017.
Some of its important feature are: -
• It supports Java 8 Date and Time.
• It provides @Repeatable annotation that can be used when we want to apply the
same annotations to a declaration or type use.
• It allows JPA annotation to be used in meta-annotations.
• It provides an ability to stream a query result.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 21


Unit-5
Daily Quiz-MCQ
1. What is JPA?
a) A programming language
b) A database management system
c) A specification for ORM in Java applications
d) A scripting language

2. Which of the following is true about JPA?


a) It is specific to a particular database management system
b) It provides a way to define database schemas
c) It simplifies object-oriented programming in Java
d) It is primarily used for front-end web development
3. Which JPA annotation is used to sp ecify the primary key
column in an entity class?
a) @PrimaryKey
b) @Id
c) @GeneratedValue
05/15/2025d) @Column Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 22
Unit-5
Daily Quiz-MCQ

4. Which annotation is used to mark a class as an entity in JPA?


a) @Entity
b) @Table
c) @Persistent
d) @EntityClass

5. What is the purpose of the @JoinColumn annotation in JPA?


a) To join multiple tables in the query
b) To specify the foreign key column in a relationship
c) To define a primary key column
d) To create an index on a column

6. Which annotation is used to define a named query in JPA?


a) @Query
b) @NamedQuery
c) @Named
d) @NamedNativeQuery
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 23
Unit-5
Daily Quiz-MCQ
MCQs - Answers and Explanations
Question 1
Answer:
c) A specification for ORM in Java applications.

Explanation:
JPA is a standard specification that defines the Java interfaces and annotations for object-relational mapping
(ORM) in Java applications. It provides a unified way to interact with relational databases using object-oriented
programming concepts.
Question 2
Answer:
c) It simplifies object-oriented programming in Java.

Explanation:
JPA simplifies database access by abstracting away the complexities of JDBC (Java Database Connectivity) and
providing an object-oriented approach to interacting with databases.
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 24
Unit-5
Daily Quiz-MCQ
MCQs - Answers and Explanations
Question 1
Answer:
c) A specification for ORM in Java applications.

Explanation:
JPA is a standard specification that defines the Java interfaces and annotations for object-relational mapping
(ORM) in Java applications. It provides a unified way to interact with relational databases using object-oriented
programming concepts.
Question 2
Answer:
c) It simplifies object-oriented programming in Java.

Explanation:
JPA simplifies database access by abstracting away the complexities of JDBC (Java Database Connectivity) and
providing an object-oriented approach to interacting with databases.
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 25
Unit-5
Daily Quiz-MCQ
Question 5
Answer:
b) To specify the foreign key column in a relationship.

Explanation:
The @JoinColumn annotation is used to specify the foreign key column in a
relationship. It allows developers to customize the column name, nullable
behavior, and other attributes of the foreign key.
Question 6
Answer:
b) @NamedQuery.

Explanation:
The @NamedQuery annotation is used to define a named query in JPA. It
allows developers to pre-define queries with a specific name and reuse them
throughout the application.
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 26
Unit-5
Overview of ORM tools
• ORM or Object Relational Mapping is a system that implements the responsibility of mapping
the Object to Relational Model. That means it is responsible to store Object Model data
into Relational Model and further read the data from Relational Model into Object Model.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 27


Unit-5
Advantage of ORM Tools

• Better System Architecture


• Reduce Coding Time
• Caching And Transaction management

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 28


Unit-5
Popular ORM tools/frameworks in Java

1.Hibernate – Open Source


2.Top Link – By Oracle
3.Eclipse Link – Eclipse Persistence Platform
4.Open JPA – By Apache
5.MyBatis – Open Source – Formerly known as iBATIS
6.You might be interested in following articles :

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 29


Unit-5
JPA

• Lecture 2
• Java Persistence API(JPA)

• JPA Feature

• Requirement entity class

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 30


Unit-5
Understanding JPA
• Lecture 2
• Java Persistence API(JPA)

• JPA Feature

• Requirement entity class

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 31


Unit-5
Java Persistence
• JPA provides a POJOAPI(JPA
persistence model for object-relational mapping.
• JPA was developed by the EJB 3.0 software expert group as part of JSR 220, but
its use is not limited to EJB software components.
• JPA can be used in web applications, Java SE applications directly, even its part
of EJB it’s not dpends on EJB containers.
• Technically JPA is just set of interfaces (Specification) and thus require an
implementation.
• It needs ORM(Object Relational Mapping) Java Persistence API implementation
to work with and persist Java Objects.
• The API defined in javax.persistence package.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 32


Unit-5
JPA Implementation

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 33


Unit-5
JPA Features

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 34


Unit-5
JPA Features
1.Provides cleaner, easier, standardized object-relational mapping.
2.JPA supports inheritance, polymorphism, and polymorphic queries.
3.Supports meta data annotations/xml descriptors to define the mapping
between Java objects and relational database.
4.It supports a rich, SQL-like query language (which is a significant extension
upon EJB QL) for both static and dynamic queries. Provides JPQL (Java
persistence query language) and native SQL queries support.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 35


Unit-5
JPA Features
5. Provides support for stored procedures since 2.1.
6. Pluggable persistence providers such as Hibernate, MyBatis etc.
7. Criteria API, which supports to build SQL queries using OOPS, so that with
the JPA criteria API it’s possible to have type safe queries that can be
checked at compile time.
8. Bean validation: the persistence provider enables Bean validation on all
entities to which annotations are applied.
9. Caching, JPA supports 2 kinds of cache first-level cache and second-
level cache to support performance tuning.
10.Better alignment with Java 8 features since JPA 2.2
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 36
Unit-5
Daily Quiz-MCQ
7. Which annotation is used to map an enumerated type property in JPA?
a) @Enumerated
b) @Enum
c) @EnumType
d) @Type

8. What is the purpose of the @Embedded annotation in JPA?


a) To define a relationship between entities
b) To specify a primary key column
c) To embed an object within an entity
d) To create a composite index on multiple columns

9. Which annotation is used to specify a discriminator column for entity inheritance in JPA?
a) @DiscriminatorColumn
b) @Inheritance
c) @Discriminant
d) @Discriminator
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 37
Unit-5
Daily Quiz-MCQ

10. What is the FetchType.LAZY attribute used for in JPA?


a) To fetch associated entities eagerly
b) To fetch associated entities lazily
c) To specify the join type in a query
d) To define the cascade type for an association

11. What is the purpose of JPA's PersistenceContext?


a) To manage database connections
b) To define database schemas
c) To store managed entities and their state
d) To execute database queries

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 38


Unit-5
Daily Quiz-MCQ
Question 7
Answer:
a) @Enumerated.

Explanation:
The @Enumerated annotation is used to map an enumerated type property in JPA. It allows
developers to specify how the enumeration values should be persisted in the database.
Question 8
Answer:
c) To embed an object within an entity.

Explanation:
The @Embedded annotation is used to specify that an object should be embedded within an
entity. It allows developers to create complex types by composing multiple attributes into a single
embedded object.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 39


Unit-5
Daily Quiz-MCQ
Question 9
Answer:
a) @DiscriminatorColumn.

Explanation:
The @DiscriminatorColumn annotation is used to specify a discriminator column for entity inheritance in JPA.
It allows developers to define a column that discriminates between different types of entities in an
inheritance hierarchy.
Question 10
Answer:
b) To fetch associated entities lazily.

Explanation:
The FetchType.LAZY attribute is used to specify that associated entities should be fetched lazily, i.e., only
when they are accessed for the first time.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 40


Unit-5
Daily Quiz-MCQ

Question 11
Answer:
c) To store managed entities and their state.

Explanation:
The PersistenceContext in JPA represents a cache of managed entities and their state. It is used to track
changes made to entities and synchronize those changes with the database.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 41


Unit-5
Requirement for Entity Class
JPA Entity Class

• An entity is a lightweight persistence domain object.

• Typically, an entity represents a table in a relational database, and each entity instance
corresponds to a row in that table.

• The primary programming artifact of an entity is the entity class, although entities can use
helper classes.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 42


Unit-5
The Point Entity Class Example

The following Point class, which represents points in the plane, is marked as an entity class, and
accordingly, provides the ability to store Point objects in the database and retrieve Point objects
from the database:
@Entity
public class Point { // String Representation:
// Persistent Fields: @Override
private int x; public String toString() {
private int y; return String.format("(%d, %d)", this.x, this.y);
}
// Constructor: }
Point (int x, int y) {
this.x = x;
this.y = y; Note: @Entity annotation, marks the class as an entity
} class.

// Accessor Methods:
public int getX() { return this.x; }
public 05/15/2025
int getY() { return this.y; } Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 43
Unit-5
Requirement for Entity Class
An entity class must follow these requirements.

• The class must be annotated with the jakarta.persistence.Entity annotation.

• The class must have a public or protected, no-argument constructor. The class may have other constructors.

• The class must not be declared final. No methods or persistent instance variables must be declared final.

• If an entity instance is passed by value as a detached object, such as through a session bean's remote business

interface, the class must implement the Serializable interface.

• Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.

• Persistent instance variables must be declared private, protected, or package-private and can be accessed directly

only by the entity class's methods. Clients must access the entity's state through accessor or business methods.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 44


Unit-5
Persistent Fields and Properties in Entity Classes
The persistent state of an entity can be accessed through either the entity's instance
variables or properties.
The fields or properties must be of the following Java language types:
• Java primitive types
• java.lang.String
• Other serializable types, including:
Wrappers of Java primitive types  java.sql.Time
java.math.BigInteger  java.sql.TimeStamp
java.math.BigDecimal
 User-defined serializable types
java.util.Date
java.util.Calendar  byte[]
java.sql.Date  Byte[]
 char[]
 Character[]
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 45
Unit-5
Daily Quiz - MCQ
12. Which of the following annotations defines a class as an entity?
A. @table
B. @entitymanager
C. @entityfactory
D. @entity
Answer: D) @entity
Explanation:
@entity annotation is used to define a class as an entity.

13. What do you mean by ORM?


A. Object relationship mapping
B. Object-oriented relationship map
C. Originator relationship mapper
D. Object-relational mapper
Answer: D) Object-relational mapper
Explanation:
ORM stands for object-relational mapper.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 46


Unit-5
Daily Quiz - MCQ
14. What is the relationship between EntityManager and entity?
A. One-to-one
B. Many-to-one
C. One-to-many
Answer: C) One-to-many
Explanation:
The relationship between EntityManager and entity is one-to-many.

15. What is the relationship between EntityManager and Query?


A. One-to-one
B. Many-to-one
C. One-to-many
Answer: C) One-to-many
Explanation:
The relationship between EntityManager and Query is one-to-many.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 47


Unit-5
Daily Quiz - MCQ
16. EntityManager and EntityTransaction have a ____- relationship?
A. One-to-one
B. Many-to-one
C. One-to-many
Answer: A) One-to-one
Explanation:
EntityManager and EntityTransaction have a one-to-one relationship.

17. EntityManagerFactory and EntityManager have which kind of relationship?


A. One-to-one
B. Many-to-one
C. One-to-many
Answer: C) One-to-many
Explanation:
EntityManagerFactory and EntityManager have a one-to-many relationship.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 48


Unit-5
Daily Quiz - MCQ
18. ____ is a factory class that generates EntityManager instances.
A. Entity
B. EntityManagerFactory
C. EntityManager
D. Persistence unit
Answer: B) EntityManagerFactory
Explanation:
EntityManagerFactory is a factory class that generates EntityManager instances.

19. The ____ serves as a logical container for a collection of entity classes.
A. Entity
B. EntityManagerFactory
C. EntityManager
D. Persistence unit
Answer: D) Persistence unit
Explanation:
The persistence unit serves as a logical container for a collection of entity classes.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 49


Unit-5
Daily Quiz - MCQ
20. JPA is based upon which of the following architecture?
A. MVC
B. Layered architecture
C. MVVM
D. Client-server architecture
Answer: B) Layered architecture
Explanation:
JPA is based upon layered architecture.

21. JPA supports how many different inheritance strategies?


A. 5
B. 8
C. 4
D. 3
Answer: D) 3
Explanation:
JPA supports three types of inheritance strategies:SINGLE_TABLE, JOINED_TABLE, and
TABLE_PER_CONCRETE_CLASS.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 50


Unit-5
Daily Quiz - MCQ
22. Does JPA supports object-oriented concept?
A. Yes
B. No
Answer: A) Yes
Explanation:
Yes, JPA support the object-oriented concept.

23. By default, the connected entities are not retrieved alongside the primary item under the ____
strategy.
A. Eager fetch
B. Lazy fetch.
Answer: B) Lazy fetch.
Explanation:
By default, the connected entities are not retrieved alongside the primary item under the Lazy Fetch
strategy.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 51


Unit-5
Persistent Fields

• By default, each field is mapped to a column with the name of the field. You can
change the default name via @Column (name="newColumnName").

• The following typical annotations can be used for fields/getter and setter
 @Id - Identifies the unique ID of the database entry

 @GeneratedValue - Together with an ID this annotation defines that this value is generated
automatically.
 @Transient - Field will not be saved in a database

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 52


Unit-5
Persistent Fields-Example
@Entity
@Column(name = "first_name")
@Table(name = "student") private String firstName;
public class Student {
@Transient
// Field will not be saved in a database
@Id
private String lastName;
@GeneratedValue(strategy = GenerationType.IDENTITY)
// getter and setter methods
@Column(name = "id") }

private int id;

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 53


Unit-5
Persistent Properties
• persistent properties mean getter and setter methods.

• If the entity uses persistent properties, the entity must follow the method
conventions of JavaBeans components( getter and setter methods).

• The object/relational mapping annotations for persistent properties must be


applied to the getter methods.

• Mapping annotations cannot be applied to fields or properties


annotated @Transient or marked transient.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 54


Unit-5
Persistent Properties
@Entity
@Table(name = "student") public void setId(int id) {
public class Student { this.id = id;
}
private int id;
private String firstName; @Column(name = "first_name")
public String getFirstName() {
@Id return firstName;
@GeneratedValue(strategy = }
GenerationType.IDENTITY)
@Column(name = "id") public void setFirstName(String firstName) {
public int getId() { this.firstName = firstName;
return id; }
} }

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 55


Unit-5
JPA
• Lecture 3
• Primary key in entity

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 56


Unit-5
Primary Keys in Entities
Every JPA entity must have a primary key. An entity may have either a simple or a
composite primary key.
Simple primary keys use the jakarta.persistence.Id annotation to denote the primary key
property or field.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 57


Unit-5
Example-Primary Keys in Entities
Configuring a JPA Entity Simple Primary Key Field
@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "first_name")
private String firstName;

// getter and setter methods


}

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 58


Unit-5
Rules for Primary Keys class
A primary key class must meet these requirements.
• The access control modifier of the class must be public.
• The properties of the primary key class must be public or protected if property-based access is used.
• The class must have a public default constructor.
• The class must implement the hashCode() and equals(Object other) methods.
• The class must be serializable.
• A composite primary key must be represented and mapped to multiple fields or properties of the entity class
or must be represented and mapped as an embeddable class.
• If the class is mapped to multiple fields or properties of the entity class, the names and types of the primary
key fields or properties in the primary key class must match those of the entity class.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 59


Unit-5
Entity Relationship Mapping
JPA allows us to define relationships between classes, e.g. it can be defined that a class is part of another class
(containment).
Classes can have one-to-one, one-to-many, many-to-one, and many-to-many relationships with other classes.
JPA provides below annotations to perform different relationships:
• @ManyToOne Relation
• @OneToMany Relation
• @OneToOne Relation
• @ManyToMany Relation

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 60


Unit-5
@ManyToOne Relation
• Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns)
which contain unique values.
• In relational databases these relations are applicable by using foreign key/primary key between tables.
• Example: from Employee to Department, Many-To-One relation is applicable. That means each record of
employee contains one department id, which should be a primary key in Department table. Here in the
Employee table, Department id is foreign Key.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 61


Unit-5
@OneToMany Relation

• In this relationship each row of one entity is referenced to many child records in other entity.
• The important thing is that child records cannot have multiple parents.
• Let us consider the above example. If Employee and Department is in a reverse unidirectional
manner, relation is Many-To-One relation. Create a JPA project in eclipse IDE
named JPA_Eclipselink_OTM. All the modules of this project are shown as follows:

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 62


Unit-5
@OneToOne Relation

• In One-To-One relationship, one item can belong to only one other item. It means each row of one entity is
referred to one and only one row of another entity.
• Let us consider the above example. Employee and Department in a reverse unidirectional manner, the relation
is One-To-One relation. It means each employee belongs to only one department. Create a JPA project in eclipse
IDE named JPA_Eclipselink_OTO. All the modules of this project are shown as follows:

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 63


Unit-5
@ManyToMany Relation
• Many-To-Many relationship is where one or more rows from one entity are associated with more than one row
in other entity.
• Let us consider an example of relation between Class and Teacher entities. In bidirectional manner, both Class
and Teacher have Many-To-One relation. That means each record of Class is referred by Teacher set (teacher
ids), which should be primary keys in Teacher table and stored in Teacher_Class table and vice versa. Here,
Teachers_Class table contains both foreign Key fields. Create a JPA project in eclipse IDE
named JPA_Eclipselink_MTM. All the modules of this project are shown as follows

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 64


Unit-5
Entity Management

Following are some of the important roles of an entity manager: -


• The entity manager implements the API and encapsulates all of them within a single interface.
• Entity manager is used to read, delete and write an entity.
• An object referenced by an entity is managed by entity manager.

Entity Operations
• Inserting an Entity
• Finding an Entity
• Updating an Entity
• Deleting an Entity

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 65


Unit-5
Daily Quiz - MCQ
24. Which of the following is the default fetch strategy in JPA?
A. Eager fetch
B. Lazy fetch.
Answer: A) Eager fetch
Explanation:
Eager Fetch is the default fetch strategy in JPA.

25. How ways are there to fetch records from the database?
A. 2
B. 3
C. 4
D. 5
Answer: A) 2
Explanation:
There are two methods for retrieving records from a database: eager fetch and lazy fetch.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 66


Unit-5
Daily Quiz - MCQ
26. ____ is used to create queries against entities to store in a relational database.
A. JPA API
B. Persistence Objects
C. ORM
D. JPQL
Answer: D) JPQL
Explanation:
JPQL is used to create queries against entities to store in a relational database.

27. What is JPQL?


A. Java Programming Querying Language
B. Java Programs Query Language
C. Java persistence Query Language
Answer: C) Java persistence Query Language
Explanation:
JPQL stands for Java Persistence Query Language.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 67


Unit-5
Daily Quiz - MCQ
26. ____ is used to create queries against entities to store in a relational database.
A. JPA API
B. Persistence Objects
C. ORM
D. JPQL
Answer: D) JPQL
Explanation:
JPQL is used to create queries against entities to store in a relational database.

27. What is JPQL?


A. Java Programming Querying Language
B. Java Programs Query Language
C. Java persistence Query Language
Answer: C) Java persistence Query Language
Explanation:
JPQL stands for Java Persistence Query Language.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 68


Unit-5
Daily Quiz-MCQ
28. The Java class encapsulates instance data and behaviors into a single unit known as an ____.
A. Object
B. Instance
C. Persistence Class
D. Java RMI
Answer: A) Object
Explanation:
The Java class encapsulates instance data and behaviors into a single unit known as an object.

29. The related entities are obtained alongside the primary item in a single query under the ____ strategy.
A. Eager Fetch
B. Lazy Fetch
Answer: A) Eager Fetch
Explanation:
The related entities are obtained alongside the primary item in a single query under the Eager Fetch strategy.
.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 69


Unit-5
Daily Quiz - MCQ
30. Which of the following inheritance strategy maps all of an entity's subclasses to the same table in
the database?
A. Table per class strategy
B. Joined table strategy
C. Single table strategy
Answer: C) Single table strategy
Explanation:
Single table Strategy maps all of an entity's subclasses to the same table in the database.

31. The ____ strategy involves creating a table for each sub entity.
A. Table per class strategy
B. Joined table strategy
C. Single table strategy
Answer: A) Table per class strategy
Explanation:
The table-per-class strategy involves creating a table for each sub-entity.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 70


Unit-5
Inserting an Entity
• Create an entity class named as StudentEntity.java under com.javatpoint.jpa.student package that contains
attributes s_id, s_name, s_age.
• After the execution of the program, the student table is generated under MySQL workbench.This table contains
the student details.To fetch data, run select * from student query in MySQL.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 71


Unit-5
Finding an Entity
• To find an entity, EntityManger interface provides find() method that searches an element on the basis of
primary key.
• Create an entity class named as StudentEntity.java under com.javatpoint.jpa.student package that contains
attributes s_id, s_name, s_age.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 72


Unit-5
Update an Entity
• Here, we will update the age of a student on the basis of primary key.
• This example contains the following steps: -
• Create an entity class named as StudentEntity.java under com.javatpoint.jpa.student package that contains
attributes s_id, s_name and s_age.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 73


Unit-5
Deleting an Entity
• To delete a record from database, EntityManager interface provides remove() method. The remove() method
uses primary key to delete the particular record.
• JPA Entity Delete Example
• Create an entity class named as StudentEntity.java under com.javatpoint.jpa.student package that contains
attributes s_id, s_name and s_age.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 74


Unit-5
Daily Quiz - MCQ
32. In what type of relationship is one entity connected with only one instance of another entity?
A. @ManyToOne Relation
B. @OneToMany Relation
C. @OneToOne Relation
D. @ManyToMany Relation
Answer: C) @OneToOne Relation
Explanation:
One entity is connected with one and only one instance of another entity in a one-to-one relationship.

33. Which of the following relationships links one entity with one or more instances of another entity?
A. @ManyToOne Relation
B. @OneToMany Relation
C. @OneToOne Relation
D. @ManyToMany Relation
Answer: B) @OneToMany Relation
Explanation:
One entity is connected with one or more instances of another entity in a one-to-many relationship.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 75


Unit-5
Daily Quiz - MCQ
32. In what type of relationship is one entity connected with only one instance of another entity?
A. @ManyToOne Relation
B. @OneToMany Relation
C. @OneToOne Relation
D. @ManyToMany Relation
Answer: C) @OneToOne Relation
Explanation:
One entity is connected with one and only one instance of another entity in a one-to-one relationship.

33. Which of the following relationships links one entity with one or more instances of another entity?
A. @ManyToOne Relation
B. @OneToMany Relation
C. @OneToOne Relation
D. @ManyToMany Relation
Answer: B) @OneToMany Relation
Explanation:
One entity is connected with one or more instances of another entity in a one-to-many relationship.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 76


Unit-5
Daily Quiz - MCQ
36. Which of the following type of cache is also known as the entity manager cache?
A. First-level cache
B. Second-level cache.
Answer: A) First-level cache
Explanation:
The first-level cache is also known as the entity manager cache.

37. Which of the following type of cache is active by default in JPA and cannot be disabled?
A. First-level cache
B. Second-level cache.
Answer: A) First-level cache
Explanation:
JPA's first-level cache is enabled by default and cannot be deactivated.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 77


Unit-5
Daily Quiz - MCQ

38. A superclass is defined as an object without a matching database table in ____ Inheritance, and its
attributes and mappings are inherited by its subclasses.
A. Table per class strategy
B. Joined table strategy
C. Single table strategy
D. Mapped Superclass

Answer: D) Mapped Superclass


Explanation:
A superclass is defined as an object without a matching database table in Mapped Superclass Inheritance, and
its attributes and mappings are inherited by its subclasses.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 78


Unit-5
JPA
• Lecture 4
• Querying Entity

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 79


Unit-5
Querying Entities
There are three basic types of JPA Queries:
1. Query, written in Java Persistence Query Language (JPQL) syntax
2. NativeQuery, written in plain SQL syntax
3. Criteria API Query, constructed programmatically via different methods
1. Query: First define the UserEntity class

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 80


Unit-5
TypedQuery

• JPA provides a special Query sub-type known as a TypedQuery. This is always preferred if we
know our Query result type beforehand. Additionally, it makes our code much more reliable
and easier to test.

This way, we get stronger typing for free, avoiding possible casting
exceptions down the road

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 81


Unit-5
NamedQuery

While we can dynamically define a Query on specific methods, they can eventually grow into a
hard-to-maintain codebase. JPA's also got us covered on this with another Query sub-type
known as a NamedQuery.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 82


Unit-5
NativeQuery
• A NativeQuery is simply an SQL query. These allow us to unleash the full power of our
database, as we can use proprietary features not available in JPQL-restricted syntax.
• This comes at a cost. We lose the database portability of our application
with NativeQuery because our JPA provider can't abstract specific details from the database
implementation or vendor anymore.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 83


Unit-5
Criteria API Query

• Criteria API Query are programmatically-built, type-safe queries – somewhat similar to JPQL
queries in syntax:

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 84


Unit-5
Query
A Query is similar in syntax to SQL

This Query retrieves the matching record from the users table and also
maps it to the UserEntity object.
There are two additional Query sub-types:
•TypedQuery
•NamedQuery
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 85
Unit-5
Daily Quiz
1. Annotation for Hibernate exceptions to be translated into Spring’s DataAccessException for consistent
exception handling?
A. Translation
B. Repowrong
C. Repository
D. None of the mentioned
2. Which is not belongs to the JPA @Entity association attributes?
A. Association validation
B. Association multiplicity
C. Association cascade behaviorwrong
D. Association direction
3.An alternative to Spring’s HibernateTemplate is
A. HibernateContext
B. Hibernate’s contextual sessions
C. All of the mentionedwrong
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 86
D. None of the mentioned Unit-5
Daily Quiz
4. Annotation for Hibernate exceptions to be translated into Spring’s DataAccessException for consistent exception
handling?
A. Translation
B. Repo
C. Repository
D. None of the mentioned
5. Annotation to find a transaction and then fail, complaining that no Hibernate session’s been bound to the
thread.
A. Transaction
B. Transactional
C. Transactions
D. None of the mentioned
6. Which of the following Is-A mapping, requires discriminator column?
A. Single Table Mapping
B. Joined Table Mapping
C. Table Per Class Mapping
D. None

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 87


Unit-5
Daily Quiz
7. JPA implementation is provided by ---?
A. Hibernate
B. Toplink
C. Ibatis
D. All of them
8.________ has stated that ideas came from several frameworks, including Hibernate and JDO.
A. Sun Microsystems
B. Java (software platform)
C. Open JDK
D. Java (programming language)

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 88


Unit-5
Daily Quiz
9. What is the Life Cycle Of A Jpa Entity?
A. New / Transient
B. Managed / Persisted
C. Detached
D. All of the above
10. Which attribute of @OneToMany is used to mark an entity as owned?
A. cascade
B. mappedBy
C. property Ref
D. None

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 89


Unit-5
Weekly Assignment
Q1. What is the Java Persistence API?[CO5]
Q2. What is the object-relational mapping?[CO5]
Q3. What are the advantages of JPA?[CO5]
Q4. What are the steps to insert an entity?[CO5]
Q5. What are the steps to find an entity?[CO5]
Q6. What are the different types of entity mapping?[CO5]
Q7. What is the role of Entity Manager in JPA?[CO5]
Q8. What are the constraints on an entity class?[CO5]
Q9. What is JPQL?[CO5]
Q10. What is the Criteria API?[CO5]

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 90


Unit-5
Topic Links
•https://www.youtube.com/watch?v=r59xYe3Vyks&list=PLS1QulWo1RIbfTjQv
Tdj8Y6yyq4R7g-Al

•https://www.digimat.in/nptel/courses/video/106105191/L01.html

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 91


Unit-5
MCQs
Q1. Which annotation is used to create the Pk-Fk relation b/w two tables?
A. JoinColumn
B. ForeignKey
C. JoinedKey
D. None of these
Q2. Object/relational metadata can be specified directly in the entity class file by using annotations, or in a separate ________
descriptor file distributed with the application.
A. Scalable Vector Graphics
B. HTML
C. XML
D. XHTML

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 92


Unit-5
MCQs
Q3. What is TRUE about the cascading and cascade mode attributes in Entity Beans?
A. Cascade mode attributes can be specified for the association annotaions (like @OneToMany) in an entity bean
B. The cascading direction is from the target entity to the source entity
C. PERSIST, DELETE and REFRESH are cascading mode attributes
D. Refresh cascade causes to refresh the target entities of a relationship when refresh is invoked on the source entity of the
relationship
Q4. Which attribute of @OneToMany is used to mark an entity as owned?
A. cascade
B. mappedBy
C. property Ref
D. Nonewrong
Q5.. What is the JPA equivalent of hibernate.cfg.xml file?
A. configuration.xml
B. persistence.xml
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 93
C. jpa.configuration.xml Unit-5
MCQs
Q6.What are the JPA @Entity association attributes?
A. Association validation
B. Association multiplicity
C. Association cascade behavior
D. Association direction
Q7.Annotation used for entity manager injection in EJB components.
A. PersistenceContext
B. Persistence
C. PersistenceCon
D. None of the mentioned

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 94


Unit-5
MCQs
Q7.Annotation used for entity manager injection in EJB components.
A. PersistenceContext
B. Persistence
C. PersistenceCon
D. None of the mentioned

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 95


Unit-5
Weekly assignment - 1
1. Explain the need for the Java Persistence API.
2. Does JPA perform tasks like access, persist, and manage data?
3. Design and Explain the object-relational mapping.
4. List out the advantages of JPA.
5. Why are embeddable classes needed in Advanced Java?

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 96


Unit-5
Weekly assignment - 2
1. List some ORM frameworks.
2. What is the JPQL?
3. What are the steps to persist an entity object?
4. What are the steps to insert an entity?
5. What are the steps to find an entity?

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 97


Unit-5
Weekly assignment - 3
1. Describe the steps to update an entity.
2. Describe the steps to delete an entity.
3. Insert a record mechanism using JPA.
4. Explain the different directions of entity mapping.
5. Explain the use of different types of entity mapping.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 98


Unit-5
Weekly assignment - 4
1. Define an orphan removal in mappings.
2. Explain the persistent life cycle of an object.
3. Discuss the different types of identifier generation.
4. Implement and discuss an entity.
5. Explain various properties of an entity and how it is implemented.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 99


Unit-5
Weekly assignment - 5
1. Discuss the role of Entity Manager in JPA.
2. Define the implementation of the constraints on an entity class.
3. Discuss the purpose of Java collections in JPA.
4. Explain the type of objects that can be stored in the JPA collections mapping.
5. What type of collections can be used in JPA?

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 100


Unit-5
Expected Questions for University Exam

Q1. What is the Java Persistence API?[CO5]


Q2. What are the steps to insert an entity?[CO5]
Q3. What is the role of Entity Manager in JPA?[CO5]
Q4. What are the constraints on an entity class?[CO5]
Q5. What are the two types of elements in Entity classes. Or in other words, list two types of access
(access) to the elements of the Entity classes. [CO5]
Q6. What is the attribute of the Entity class in JPA terminology? [CO5]
What data types are allowed in the attributes of the Entity class (fields or properties)? [CO5]
Q7. What is the Embeddable class? [CO5]
Q8. Can the Embeddable class contain another Embeddable class? [CO5]

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 101


Unit-5
Old Question Papers

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 102


Unit-5
Old Question Papers

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 103


Unit-5
Recap of Unit
• Unit start with examines how Object-Relational Mapping (ORM) frameworks and

technologies simplify database development.


• The course concludes key JPA concepts, like an EntityManager, how to create

advanced queries using Java Persistence Query Language (JPQL), and examining

how to structure complex entity relationships.

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 104


Unit-5
References

05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 105


Unit-5
Thanks
05/15/2025 Shweta Singh AMICSE0601/ACSE0601/ACSEHO601 106
Unit-5

You might also like