Master the most popular Java framework for building enterprise-level web applications.
Spring Data JPA simplifies database operations by providing a powerful abstraction over JPA (Java Persistence API). It reduces boilerplate code and makes database interactions more intuitive and maintainable.
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column
private String description;
@Column(precision = 10, scale = 2)
private BigDecimal price;
// Constructors, getters, and setters
public Product() {}
public Product(String name, String description, BigDecimal price) {
this.name = name;
this.description = description;
this.price = price;
}
// Getters and setters...
}
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Derived query methods
List<Product> findByNameContaining(String name);
List<Product> findByPriceBetween(BigDecimal minPrice, BigDecimal maxPrice);
// Custom JPQL query
@Query("SELECT p FROM Product p WHERE p.price > :minPrice")
List<Product> findExpensiveProducts(@Param("minPrice") BigDecimal minPrice);
// Native SQL query
@Query(value = "SELECT * FROM products ORDER BY price DESC LIMIT 5", nativeQuery = true)
List<Product> findTop5ExpensiveProducts();
}