Session02 - Spring Data JPA
Session02 - Spring Data JPA
Objectives
• ORM
• Spring Data JPA
• Validation
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 = ?";
@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);
// 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
@Size Field size should be less than or greater than the speci ied ield size
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