KEMBAR78
01 Spring DataJpa MyCustom Notes | PDF | Databases | Data Management Software
0% found this document useful (0 votes)
7 views12 pages

01 Spring DataJpa MyCustom Notes

Uploaded by

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

01 Spring DataJpa MyCustom Notes

Uploaded by

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

Spring DataJpa

1.what is persistence?

storing and manging data for long time called persistence

2.what is persistence store

The place where we can store and manage data for long time called persistence store like database

it support CURD operation C=create .Insert

U=update .update

R=read .select

D=delete .delete

3.what is persistence technology or framework

it is a technology or framework using which we devlope persistence logic to perform persistence
operation (curd).

4.why we can’t use for persistence or what is the limitation of files

files are not good for for persistence that’s why we don’t use in medium and large scale project

because files don’t have security for data

it does not support constraint for duplicate and unique data

data retrieve and update complex

we can’t keeps file interact with each other

we can’ t campare one file with another

5. limitations of JDBC

 Connection Handling: Properly managing and closing connections can be challenging, leading to
potential resource leaks

changing the DB in project is complex

it’s increasing the boilerplate code

Exception Handling is mandatory

JPA=java persistence API

ORM=object relation mapping


5.what is ORM

The process of mapping/linking java class with database table and java class properties with database
table column and making object of java class represent records of table having synchronization between
them called ORM

Synchronize between object and database table is nothing but connecting with each other when we
do operation(curd) on object or db table it reflect in db table or object .

6.Adventages of mapping

No need to write SQL query

Allow to develope object based persistence logic as database independent persistence logic

we can work with object directly

change the database in project easy

Dynamic schema generation(table ,sequence)

7.Limitation of ORMS

when we do large number of operation at a time from database table then more and more
object created for entity class this may leads to memory issue or application may crass

 Performance Overhead: Abstraction layer can slow down performance.

 Complex Queries: Less efficient for intricate or highly customized queries.

 Learning Curve: Requires understanding the ORM framework.

 Abstraction Leakage: Need for underlying database knowledge can persist.

 Limited Database Support: Not all databases or features are equally supported.

 Debugging Challenges: Debugging ORM-generated queries is harder.

 Schema Changes: Frequent schema changes are difficult to manage.

8.When we choose SQL and no SQL database ?

when application dealing with formatted data and fixed attribute it refers to SQL d/b,it stored all the
data in table form.

when application dealing with unstructured data and Dynamically Growing attribute and size that
refers to NOSql D/B it maintain data the form of documents ,tree and graph etc…
the Main module is Spring data

its imporatant sub-module is

A.Spring data jpa ->its provide abstraction on ORM framework like Hibernate ,ibatis
etc ..

B.Spring data Jdbc ->it provide abstraction in JDBC technology

C.Spring data mongoDB ->it provide abstraction on mongodb api

9.what is JPA(java persistence API)

It is a specification provide rule and guideline to developing ORM software like Hibernate

10.what is difference between

Object-Relational Mapping (ORM):

 Definition: ORM is a programming technique that allows developers to map objects in


their code to relational database tables. It abstracts the database interactions, making it
easier to work with.
 Purpose: The main purpose of ORM is to simplify database operations by allowing
developers to work with objects instead of SQL queries.
 Examples: Hibernate, MyBatis, and EclipseLink are some popular ORM frameworks.

Java Persistence API (JPA):

 Definition: JPA is a specification for ORM in Java. It defines a standard way to map
Java objects to relational databases.
 Purpose: The main purpose of JPA is to provide a set of guidelines and specifications for
ORM frameworks. It standardizes the way Java applications interact with databases.
 Examples: Hibernate, EclipseLink, and OpenJPA are implementations of the JPA
specification.

JpA gives rule and guideline to ORM for developing persistance logic

DATA JPA
Spring Data JPA simplifies database access in Spring Boot applications by providing an abstraction
layer over the Java Persistence API (JPA).
It enables seamless integration with relational databases using Object-Relational Mapping (ORM),
eliminating the need for boilerplate SQL queries.

With features like automatic query generation, JPQL support, and easy repository management,
Spring Data JPA enhances efficiency in developing scalable and high-performance applications.

Persistance

persistence means saving Java objects into a database so that their data stays even after the
application stops.

Term Meaning

Persistence Storing Java objects (entities) into a database

Entity A Java class mapped to a database table (@Entity)

Persistence Context A memory space where JPA tracks changes to entities before saving them

EntityManager The tool that handles saving, updating, and deleting entities

 It reduces boilerplate code—you don’t need to write SQL manually.

 It tracks changes to your objects and syncs them with the database.

 It improves performance using caching (first-level cache via persistence context).

ORM
ORM stands for Object-Relational Mapping. It’s a technique that lets you map Java objects
(like classes) to database tables—so you can work with data using Java code instead of writing
SQL manually.

🔄 How It Works

 Each Java class becomes a table


 Each object becomes a row
 Each field becomes a column

 ORM is the idea of mapping Java classes to database tables.

 JPA is a specification that defines how ORM should work in Java.

 Spring Data JPA is a tool that makes JPA easier to use in Spring apps.

Disadventages
🚧 Issue 💬 Why It Matters
ORM adds abstraction, which can slow down complex or bulk
Performance Overhead
operations
Limited SQL Control You lose fine-grained control over query optimization and indexing
Errors can be harder to trace due to multiple layers (JPA → Hibernate
Complex Debugging
→ JDBC)
Learning Curve Understanding lazy loading, cascading, and entity states takes time
Schema Mismatch If your entity class and DB schema get out of sync, it can cause
Risks runtime issues
Overkill for Simple For small projects, ORM might be too heavy—JDBC could be simpler
Apps and faster

Entity manager
In Spring Boot (using JPA), the EntityManager is the main interface that handles all
interactions between your Java objects (called entities) and the database.

When to Prefer EntityManager Over JpaRepository


 You need complex joins or subqueries
 You want to detach or merge entities manually
 You’re working with legacy databases or non-standard schemas
 You want to optimize performance with custom flush or batch logic

Think of it as the gatekeeper that lets you:

 Save (persist)
 Update (merge)
 Delete (remove)
 Fetch (find, createQuery) Java objects directly from/to the database.
 🔧 Key Responsibilities

Method What It Does


persist() Saves a new entity to the database
merge() Updates an existing entity
remove() Deletes an entity
find() Retrieves an entity by primary key
createQuery() Runs custom JPQL queries

🛠️How to Use It in Spring Boot

You can inject it using:

java
@Autowired
private EntityManager entityManager;

Then use it like:

java
User user = entityManager.find(User.class, 1L);
entityManager.persist(new User("Alice", "alice@email.com"));

🧩 Behind the Scenes

 Spring Boot auto-configures the EntityManagerFactory.


 The EntityManager works inside a persistence context, which tracks changes to entities
and syncs them with the database during transactions.

💡 When to Use EntityManager

 When you need custom queries or fine-grained control


 For batch operations or native SQL
 When JpaRepository methods aren’t flexible enough

interfaces
Core Repository Interfaces

Interface Purpose

CrudRepository Basic CRUD operations

JpaRepository CRUD + JPA-specific features (paging, sorting)

PagingAndSortingRepository Adds pagination and sorting support

🔧 Common Methods in JpaRepository

Method Use Case Example

save(entity) Save or update a record

saveAll(entities) Bulk insert/update

findById(id) Fetch a record by primary key

findAll() Get all records

findAllById(ids) Get multiple records by IDs

delete(entity) Delete a specific record

deleteById(id) Delete by ID

deleteAll() Remove all records

existsById(id) Check if a record exists

count() Get total number of records

🔍 Derived Query Methods (Auto-generated by method name)

Method Name Example JPQL Equivalent


findByName(String name) SELECT u FROM User u WHERE u.name = ?1

findByAgeGreaterThan(int age) WHERE age > ?1

findByEmailContaining(String text) WHERE email LIKE %?1%

findByStatusTrue() WHERE status = true

findByCreatedDateBetween(...) WHERE date BETWEEN ?1 AND ?2

You can find more keyword-based query options in Spring’s official documentation.
🧠 Real-World Use Cases

Scenario Method(s) to Use

User Registration save()

Login Validation findByEmail() or findByUsername()

Dashboard Listing findAll() with pagination/sorting

Profile Update save()

Delete Account deleteById()

Search Feature findByNameContaining()

Analytics count(), findByCreatedDateBetween()

@Query

We use the @Query annotation when we need more flexibility and control than what derived
query methods (findByName(), findByStatusTrue(), etc.) offer.

✅ Benefits of @Query

Reason Description

Write complex JPQL or native SQL queries not supported by method naming
Custom Query Logic
conventions

Join Operations Easily perform joins across multiple tables/entities


Reason Description

Filtering &
Apply conditions like GROUP BY, HAVING, or advanced WHERE clauses
Aggregation

Projection Queries Return specific columns (DTOs) rather than entire entity objects

Native SQL Support Use real SQL syntax via nativeQuery = true

Versioning
>It keeps track when the object load and modified by using
hibernate logic for that we need to add @version
Timestamp
>time stamp track the object when it will saved and last
updated fot this we should annotate with
@creationTimestamp
@updationTimestamp

Association
In Spring Data JPA, association refers to the way entities (Java classes mapped to database
tables) are linked together to reflect real-world relationships between data. These associations
are crucial for modeling complex data structures and enabling seamless navigation between
related entities.

association simply means how one entity (Java class) is linked or related to another. These
links help represent real-world relationships in your database.
Types of Associations in JPA

Annotation Relationship Type Example Scenario


@OneToOne One entity to one entity A User has one Profile
@OneToMany One entity to many others A Department has many Employees
@ManyToOne Many entities to one Many Orders belong to one Customer
@ManyToMany Many entities to many Many Students enrolled in many Courses

🧠 Why Associations Matter

 Reflect real-world relationships in your domain model


 Enable automatic joins and navigation between entities
 Simplify querying and data manipulation
 Support cascading operations (e.g., saving parent and child together)

🛠️Example: One-to-Many Association

java
@Entity
public class Department {
@Id
private Long id;

@OneToMany(mappedBy = "department")
private List<Employee> employees;
}

@Entity
public class Employee {
@Id
private Long id;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}

This setup allows you to:

 Fetch all employees of a department


 Access the department from an employee
 Automatically manage foreign keys and joins

🧩 Unidirectional vs Bidirectional
Type Description
Unidirectional Only one entity knows about the relationship
Bidirectional Both entities reference each other

You might also like