Working with Spring Data JPA
Working with Spring Data JPA
Spring Data JPA removes most of the database plumbing from a Boot application. You define an entity, create a tiny repository interface, and Spring Data provides the implementation at runtime, complete with CRUD operations, query methods, and paging.
Define the entity
An entity is a class annotated with @Entity that maps to a table. Fields map to columns, and the primary key is marked with @Id. If you run with an in-memory database like H2, Boot can create the schema for you.
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
protected Customer() {}
}
Create the repository
Extend JpaRepository<Customer, Long> and you immediately get save, findAll, findById, deleteById, and paging support. Spring Data generates the implementation from the interface, so there is no service code to write for basic persistence.
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByEmailContaining(String part);
}
Derived query methods
Describe what you want in the method name and Spring Data derives the query: findByEmailContaining, countByStatus, findTop5ByOrderByCreatedAtDesc. Behind the scenes it builds JPQL, and you also have @Query for custom JPQL or native SQL when naming conventions are not enough.
Database configuration
Set the datasource in application.properties with spring.datasource.url, username, and password, plus spring.jpa.hibernate.ddl-auto=update during development so Hibernate aligns tables with entities. Switch to explicit migrations in production.
Transactions
Spring Data repository methods are transactional by default. For multi-step operations, annotate a service method with @Transactional so that a failure rolls back all writes. Keep transactions at the service layer, not inside controllers.
Key Points
@Entitymaps a class to a table;@Idmarks the primary key.- Interface repositories built on
JpaRepositoryprovide CRUD instantly. - Derived method names generate JPQL queries automatically.
- Configure the datasource and DDL strategy in
application.properties. - Put
@Transactionalon service methods for multi-step writes.