0% found this document useful (0 votes)
4 views

Session02 - Spring Data JPA

bai 2 data

Uploaded by

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

Session02 - Spring Data JPA

bai 2 data

Uploaded by

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

Session 02: Spring Data JPA

Objectives
• ORM
• Spring Data JPA
• Validation

R2S Academy - Internal Use 2


ORM (1)
What is ORM?
• ORM (Object-Relational Mapping) is a programming technique that simplifies
the interaction between relational databases and object-oriented
programming languages like Java

R2S Academy - Internal Use 3


ORM (2)
How Does ORM Work?
• Mapping: You define how your Java classes (entities) correspond to
database tables using annotations or configuration files.
• Persistence Provider: The ORM framework provides a persistence provider
that interacts with the database based on your object mappings.
• CRUD Operations: You perform CRUD (Create, Read, Update, Delete)
operations on your objects using ORM methods that translate them into
appropriate SQL statements.

R2S Academy - Internal Use 4


ORM (3)
Sample
• We have a simple application managing Product entities with id, name, and price
attributes. Let's compare how to achieve basic operations without and with an ORM.
• Product Table
Without ORM Using ORM
@Entity
public class Product {
CREATE TABLE product ( @Id
id INT PRIMARY KEY IDENTITY(1,1), @GeneratedValue(strategy = GenerationType.IDENTITY)
name VARCHAR(255) NOT NULL, private Long id;
price DECIMAL(10,2) NOT NULL private String name;
); private Double price;
// Getters and setters (omitted for brevity)
}

R2S Academy - Internal Use 5


ORM (4)
Sample
• CRUD operations - Create
Without ORM Using Spring Data JPA

public void createProduct(Product product) throws SQLException {


String sql = "INSERT INTO product (name, price) VALUES (?, ?)";

try (Connection conn = getConnection(); public interface ProductRepository extends


PreparedStatement ps = conn.prepareStatement(sql)) {
JpaRepository<Product, Long> {
}
ps(1, product.getName());
ps.setBigDecimal(2, product.getPrice());
Product savedProduct = productRepository.save(product);
ps.executeUpdate();
}
}

R2S Academy - Internal Use 6


ORM (5)
Sample
• CRUD operations - Read
Without ORM Using Spring Data JPA
public Product getProductById(long id) throws SQLException {
String sql = "SELECT * FROM product WHERE id = ?";
Product product = null;

try (Connection conn = getConnection(); public interface ProductRepository extends


PreparedStatement ps = conn.prepareStatement(sql)) { JpaRepository<Product, Long> {
}
ps.setLong(1, id);
ResultSet resultSet = ps.executeQuery();
Optional<Product> product =
productRepository.findById(id);
if (resultSet.next()) {
}
}

return product;
}
R2S Academy - Internal Use 7
ORM (6)
Sample
• CRUD operations - Update
Without ORM Using Spring Data JPA
public void updateProduct(Product product) throws
SQLException {
String sql = "UPDATE product SET name = ? WHERE id = ?";

try (Connection conn = getConnection(); public interface ProductRepository extends


PreparedStatement ps = conn.prepareStatement(sql)) { JpaRepository<Product, Long> {
}
ps.setString(1, product.getName());
productRepository.save(existingProduct);
ps.executeUpdate();
}
}

R2S Academy - Internal Use 8


ORM (7)
Sample
• CRUD operations - Delete
Without ORM Using Spring Data JPA

public void deleteProduct(long id) throws SQLException {


String sql = "DELETE FROM product WHERE id = ?";
public interface ProductRepository extends
try (Connection conn = getConnection(); JpaRepository<Product, Long> {
PreparedStatement ps = conn.prepareStatement(sql)) { }
ps.setLong(1, id);
ps.executeUpdate(); productRepository.deleteById(id);
}
}

R2S Academy - Internal Use 9


Spring Data JPA (1)
What is Spring Data JPA
• It is a part of the larger Spring Data project which makes it easier to implement data access
layers for various persistence stores.
• Spring Data JPA is a repository system that creates automatic Data Access Objects (DAOs)
for you at compile time and uses an ORM like Hibernate in these DAOs (Spring Data JPA is
not an ORM)

R2S Academy - Internal Use 10


Spring Data JPA (2)
Key Concepts
• Entities: POJOs (Plain Old Java Objects) annotated with @Entity that map to
database tables.
• Example
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;
// Getters and setters (omitted for brevity)
}

R2S Academy - Internal Use 11


Spring Data JPA (3)
Key Concepts
• Repositories: Interfaces extending JpaRepository<T, ID> provide pre-defined
methods for CRUD operations on entities of type T with an ID of type ID.
• Example @Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;
// Getters and setters (omitted for brevity)
}
R2S Academy - Internal Use 12
Spring Data JPA (4)
Key Concepts
• Derived Queries: Simple method naming conventions in repositories can automatically
generate JPQL (Java Persistence Query Language) queries based on method names.
• Example
public interface ProductRepository extends JpaRepository<Product, Long> {
// Derived query by name (using method name convention)
List<Product> findByNameContaining(String name);

// Derived query by price range (using method name convention)


List<Product> findByPriceBetween(Double minPrice, Double maxPrice);

// a custom JPQL query defined using the @Query annotation for more complex scenarios.
@Query("SELECT p FROM Product p WHERE p.name LIKE ?1 AND p.price > ?2")
List<Product> findByNameLikeAndPriceGreaterThan(String name, Double minPrice);
}
Reference: https://docs.spring.io/spring-data/jpa/reference/jpa/query-methods.html
R2S Academy - Internal Use 13
Validation (1)
Introduction
• Validation annotations that can be applied to the data fields within your Entity/DTO
class, and allows you to follow specific rules and conditions for fields in which we are
applying validators to meet your custom constraints
• Example

R2S Academy - Internal Use 14


Validation (2)
Annotations
• The following annotations
Annotation Usages

@NotNull Not be null but can be empty

@NotEmpty Not be null and not empty

@NotBlank Not be null and not empty and not blank

@Min Given Minimum value has to be satis ied

R2S Academy - Internal Use 15


f
Validation (3)
Annotations
• The following annotations
Annotation Usages

@Max Given Maximum value has to be satis ied

@Size Field size should be less than or greater than the speci ied ield size

@Email Email can be validated with this

@Pattern Given RegEx Pattern has to be satis ied.

R2S Academy - Internal Use 16


f
f
f
f
Validation (4)
<dependency>
Example
<groupId>org.springframework.boot</groupId>
• Configuration for Validators <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
• Code
@NotBlank(message = "Employee name can't be left empty")
private String name;

@Min(value = 18, message = "Minimum working age 18")


@Max(value = 60, message = "Maximum working age 60")
private Integer age;

@Email(message = "Please enter a valid email Id")


@NotNull(message = "Email cannot be NULL")
private String email;

@Pattern(regexp = "^[0-9]{5}$", message = "Employee postal code must be a 5-digit number.")


private String postalCode;

@Size(min = 10, max = 100,


message = "Address should have a length between 10 and 100 characters.")
private String address;
R2S Academy - Internal Use 17
Validation (5)
Example
• To collect all the errors, we need to have an “ExceptionHandler” and it is given below
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException exception,
HttpHeaders httpHeaders, HttpStatus httpStatus,
WebRequest webRequest){
Map<String, Object> objectBody = new LinkedHashMap<>();
objectBody.put("Current Timestamp", new Date());
objectBody.put("Status", httpStatus.value());

// Get all errors


List<String> exceptionalErrors = exception.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());

objectBody.put("Errors", exceptionalErrors);
return new ResponseEntity<>(objectBody, httpStatus);
}
}
R2S Academy - Internal Use 18
Keeping up those inspiration and the enthusiasm in the learning path.
Let confidence to bring it into your career path for getting gain the success as
your expectation.

Thank you
Contact
- Name: R2S Academy
- Email: [email protected]
Questions and Answers
- Hotline/Zalo: 0919 365 363
- Website: https://r2s.edu.vn
- Fanpage: https://www.facebook.com/r2s.tuyendung

R2S Academy - Internal Use 19

You might also like