Spring Data JPA
Imagine you have a remote control. You don't need to know how the TV works internally – you just press buttons. Spring Data JPA is like that remote control for your database. It handles all the complex JPA code so you can focus on your business logic.
Spring Data JPA provides repository interfaces that already have methods for common operations like save, find, delete. You just create an interface and Spring provides the implementation automatically.
Here is how simple it is:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;
private String category;
// getters, setters
}
// That's it! No implementation class needed
public interface ProductRepository extends JpaRepository {
// Custom query methods - Spring implements these!
List findByCategory(String category);
List findByPriceBetween(Double min, Double max);
List findByNameContaining(String keyword);
@Query("SELECT p FROM Product p WHERE p.price > :price")
List findExpensiveProducts(@Param("price") Double price);
@Modifying
@Query("UPDATE Product p SET p.price = p.price * 1.1 WHERE p.category = :category")
int increasePriceByCategory(@Param("category") String category);
}
Using the repository in your service:
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public Product saveProduct(Product product) {
return productRepository.save(product);
}
public List getAllProducts() {
return productRepository.findAll();
}
public Product getProductById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Product not found"));
}
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
public List findByCategory(String category) {
return productRepository.findByCategory(category);
}
}
JpaRepository provides these methods out-of-the-box:
- save() – insert or update
- findById() – get by primary key
- findAll() – get all records
- count() – total records
- delete() – delete entity
- deleteById() – delete by id
- existsById() – check if exists
Two Minute Drill
- Spring Data JPA eliminates boilerplate code by providing repository implementations.
- Extend JpaRepository to get CRUD methods automatically.
- Define custom query methods by following naming conventions (findBy...).
- Use @Query for complex queries.
- @Modifying with @Query for UPDATE/DELETE operations.
Need more clarification?
Drop us an email at career@quipoinfotech.com
