0% found this document useful (0 votes)
4 views10 pages

JAVA Prep

The document provides an overview of lambda expressions in Java, highlighting their role as anonymous functions introduced in Java 8 to facilitate functional programming. It also discusses the benefits of lambda expressions, such as reducing boilerplate code and improving readability, as well as their application in JPA with named queries and repository interfaces. Additionally, it covers key concepts of ORM, the purpose of the @Version annotation, and JPQL, emphasizing their importance in managing database interactions and relationships.

Uploaded by

ravij007
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)
4 views10 pages

JAVA Prep

The document provides an overview of lambda expressions in Java, highlighting their role as anonymous functions introduced in Java 8 to facilitate functional programming. It also discusses the benefits of lambda expressions, such as reducing boilerplate code and improving readability, as well as their application in JPA with named queries and repository interfaces. Additionally, it covers key concepts of ORM, the purpose of the @Version annotation, and JPQL, emphasizing their importance in managing database interactions and relationships.

Uploaded by

ravij007
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

JAVA prep

LAMBDA EXPRESSIONS:

what is lambda expression in java

A lambda expression in Java is anonymous function—a block of code that can


be passed around and executed later. It's a feature introduced in Java 8 and is
mainly used to enable functional programming and make code more concise,
especially when working with functional interfaces.

Not having Name


Not having modifiers
Not having any returntype.

Ex:
public void m1(){
sopln(“hello”);
}
Lambda------
()->sopln(“hello”);

EX-2:
Public void add(int a,int b){
Sopln(a+b);
}
Lambda---
(int a,int b)->sopln(a+b)
---some times based on the context compiler can guess the types
automatically---
(a,b)->sopln(a+b)

Ex3:
Public int getlength(String s){
return length();
}

----
(String s)->return [Link]();
(s)->[Link]();

(parameters) -> expression

(parameters) -> { statements }

Benefits of Lambda Expressions


 Less boilerplate code
 Improves readability
 Enables functional-style programming
 Great for use with streams and collections
To enable functional programming in java.
Write more readable, concise &maintainable code .
To use apis very easily and effectively.
To enable parallel processing.

Functional programming (FP) is a programming paradigm (style or way of


writing code) where you build programs by using functions — especially pure
functions — and avoiding shared state, mutable data, and side effects.

A function is a block of code that performs a specific task.


🔹 Functional Programming in Java
Java wasn't originally a functional language, but since Java 8, it added features
like:
 Lambda Expressions
 Streams API
 Functional Interfaces

🔹 Why Do We Need Lambda Expressions in Java?


Lambda expressions were introduced in Java 8 to bring functional
programming features into Java. The main reason: to simplify the code,
especially when working with functional interfaces, collections, and
multithreading.
Key Reasons We Need Lambda Expressions:

1. Reduce Boilerplate Code

Without Lambda:

Runnable r = new Runnable() {


public void run() {
[Link]("Running...");
}
};

With Lambda:

Runnable r = () -> [Link]("Running...");

2. Make Code More Readable & Concise


Especially when working with collections and streams.
2. Enable Functional Programming Style
3. Work Smoothly with Functional Interfaces

[Link] query in jpa


In JPA, named queries are a way to define static queries at the entity level using
annotations. Named queries are pre-defined and can be reused multiple times,
providing a convenient way to centralize and manage query definitions.
There are two main annotations used for defining named queries:
@NamedQuery for JPQL (Java Persistence Query Language) queries and
@NamedNativeQuery for native SQL queries.

[Link] between jpa repository and curd repository

In Spring Data JPA, both JpaRepository and CrudRepository are interfaces that
provide methods for performing CRUD (Create, Read, Update, Delete)
operations on entities. However, there are important differences between
them in terms of the additional functionality and methods they offer. Here’s a
detailed comparison of JpaRepository and CrudRepository:

CrudRepository
CrudRepository is a basic interface provided by Spring Data that offers CRUD
functionality for the entity class being managed. It provides a simple API for
standard CRUD operations.
Key Features of CrudRepository:
1. Basic CRUD Operations:
o save(S entity): Saves a given entity.
o saveAll(Iterable<S> entities): Saves all given entities.
o findById(ID id): Retrieves an entity by its id.
o existsById(ID id): Checks whether an entity with the given id exists.
o findAll(): Returns all entities.
o findAllById(Iterable<ID> ids): Returns all entities with the given ids.
o count(): Returns the number of entities.
o deleteById(ID id): Deletes the entity with the given id.
o delete(T entity): Deletes a given entity.
o deleteAll(Iterable<? extends T> entities): Deletes all given entities.
o deleteAll(): Deletes all entities.
JpaRepository
JpaRepository extends CrudRepository and PagingAndSortingRepository. It
provides JPA-specific methods along with the CRUD and pagination/sorting
functionalities.

This interface is more feature-rich and includes methods for batch operations,
flushing, and deleting in bulk.
Key Features of JpaRepository:
1. Extended CRUD Operations:
o Inherits all methods from CrudRepository.
2. Batch Operations:
o saveAndFlush(S entity): Saves an entity and flushes changes
instantly.
o saveAllAndFlush(Iterable<S> entities): Saves all given entities and
flushes changes instantly.
3. Flushing:
o flush(): Flushes all pending changes to the database.
4. Delete in Bulk:
o deleteAllInBatch(): Deletes all entities in a batch.
o deleteAllInBatch(Iterable<T> entities): Deletes all given entities in
a batch.
5. Pagination and Sorting:
o findAll(Pageable pageable): Returns a Page of entities meeting the
paging restriction provided in the Pageable object.
o findAll(Sort sort): Returns all entities sorted by the given options.

[Link] type of collections used in jpa


List, Set, Map, and Collection
Annotations like @OneToMany, @ManyToMany, and @ElementCollection

[Link] stands for Object-Relational Mapping

Key Concepts of ORM:


1. Objects to Relational Mapping:
o ORM bridges the gap between the object-oriented model used in
application code and the relational model used in databases. It
maps object instances to database tables and vice versa.
2. Abstraction of Database Operations:
o ORM frameworks abstract away the low-level SQL statements
required to interact with the database. Instead, developers work
with high-level object-oriented APIs to perform CRUD operations.
3. Automatic Schema Generation:
o ORM frameworks often provide tools to automatically generate
database schema based on the object model defined in the
application code. This reduces the need for manual database
schema management.
4. Support for Relationships:
o ORM frameworks facilitate the mapping of relationships between
objects (such as one-to-one, one-to-many, many-to-many) to
corresponding database relationships (foreign keys, join tables).
5. Performance Optimization:
o Advanced ORM frameworks optimize database access by
generating efficient SQL queries, caching query results, and
supporting lazy loading of related objects.

[Link] of @Version Annotation:

In JPA (Java Persistence API), the @Version annotation serves a specific


purpose related to optimistic locking. Optimistic locking is a strategy used to
prevent data conflicts in concurrent transactions by checking whether the data
has been modified since it was last read.
1. Optimistic Locking:
o The primary purpose of @Version is to facilitate optimistic locking
in JPA. When an entity is marked with @Version, JPA uses a
version attribute to track changes to the entity.
2. Automatic Versioning:
o When an entity with a @Version annotated attribute is updated,
JPA automatically increments the version attribute value. This
allows JPA to detect concurrent modifications to the same entity
during transaction commits.
3. Conflict Detection:
o During a transaction commit, JPA compares the version value of
the entity being updated with the version value in the database. If
the version values differ, it indicates that another transaction has
modified the entity concurrently.
4. Exception Handling:
o If a concurrent modification is detected (i.e., the version in the
database does not match the expected version), JPA throws an
OptimisticLockException. This allows the application to handle the
situation, such as by retrying the operation or informing the user
about the conflict.
[Link] (Java Persistence Query Language)

is a query language defined by the JPA (Java Persistence API) specification. It is


used to query entities stored in a relational database using object-oriented
syntax and semantics, rather than directly querying database tables using SQL.

JPQL provides a way to perform database queries based on the entity model
defined by JPA entity classes and their relationships.

Key Features and Characteristics of JPQL:


1. Object-Oriented Query Language:
o JPQL allows developers to write queries using entity names,
attributes, and relationships defined in the entity classes. This
object-oriented approach makes it more intuitive for Java
developers to query and manipulate data.
2. Database Independence:
o JPQL queries are written independently of the underlying
database SQL dialect. This allows applications to remain portable
across different databases supported by the JPA provider (such as
Hibernate, EclipseLink, etc.).
3. Entity-Centric Queries:
o Queries in JPQL are performed on JPA entity classes rather than
directly on database tables. This abstraction simplifies the
interaction with the database and promotes a more object-
oriented design.
4. Syntax Similarity to SQL:
o While JPQL syntax is similar to SQL, it operates on entity objects
and their persistent fields rather than database tables and
columns. JPQL queries use keywords such as SELECT, FROM,
WHERE, JOIN, GROUP BY, ORDER BY, etc., similar to SQL.
5. Parameterized Queries:
o JPQL supports parameterized queries using named parameters
(:parameterName) or positional parameters (?1, ?2, etc.). This
allows developers to write reusable queries with parameters that
can be set dynamically.

JPQL Keywords

6. SELECT: Specifies the entities or fields to retrieve.


7. FROM: Defines the entity class to query from.
8. WHERE: Adds conditions to filter the query results.
9. ORDER BY: Orders the results based on specified fields.
10. GROUP BY: Groups results based on specified fields.
11. HAVING: Applies conditions on grouped results.
12. JOIN: Joins related entities.
o

16. difference between one to many and may to many


Definition: In a one-to-many relationship, a single record in one table is
associated with multiple records in another table. However, each record in the
second table is associated with only one record in the first table.

Definition: In a many-to-many relationship, multiple records in one table are


associated with multiple records in another table.

You might also like