Log SQL (use logging.level.org.hibernate.SQL=DEBUG in prod)
spring.jpa.open-in-view
Set false in services
2. Creating Entity Classes (@Entity, @Table)
Example: JPA entity with index and audit timestamps
@Entity@Table(name="orders", indexes=@Index(columnList="customer_id,status"))public class Order { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(nullable=false) private String reference; @Enumerated(EnumType.STRING) private OrderStatus status; @Column(name="customer_id") private Long customerId; @CreationTimestamp private Instant createdAt; // getters/setters/protected no-arg ctor}
3. Defining Primary Keys
Strategy
Behavior
IDENTITY
DB autoincrement; one INSERT per save
SEQUENCE
Uses DB sequence; supports batching
TABLE
Portable but slower
UUID
Java/DB-side generated UUID
AUTO
Provider-chosen
4. Mapping Columns (@Column annotations)
Attribute
Use
name
DB column name
nullable
Default true
unique
Adds unique constraint at DDL
length
VARCHAR size
precision/scale
Numeric
insertable/updatable
Read-only fields
columnDefinition
Raw DDL fragment
5. Defining Relationships
Annotation
Cardinality
Default Fetch
@OneToOne
1:1
EAGER
@OneToMany
1:N
LAZY
@ManyToOne
N:1
EAGER (override to LAZY)
@ManyToMany
M:N
LAZY
6. Creating Repository Interfaces
Example: Repository with derived query methods
public interface OrderRepository extends JpaRepository<Order, Long> { Optional<Order> findByReference(String reference); List<Order> findByStatusAndCustomerId(OrderStatus s, Long customerId); long countByStatus(OrderStatus status);}
Interface
Provides
Repository<T,ID>
Marker only
CrudRepository
CRUD
PagingAndSortingRepository
+Page/Sort
JpaRepository
+flush, batch, getReferenceById
ListCrudRepository
List instead of Iterable
7. Using Derived Query Methods
Keyword
SQL
findBy / readBy / queryBy
SELECT
findFirst10ByOrderByCreatedAtDesc
LIMIT + ORDER BY
findByEmailContainingIgnoreCase
LIKE
findByAgeBetween
BETWEEN
findByStatusIn
IN
existsBy / countBy / deleteBy
EXISTS / COUNT / DELETE
8. Writing Custom JPQL Queries (@Query)
Example: Custom JPQL select and update queries
public interface OrderRepository extends JpaRepository<Order, Long> { @Query("select o from Order o where o.status = :s and o.total > :min") List<Order> findHighValue(@Param("s") OrderStatus s, @Param("min") BigDecimal min); @Modifying @Query("update Order o set o.status='CANCELLED' where o.id = :id") int cancel(@Param("id") Long id);}
9. Using Native SQL Queries
Example: Native query with interface projection
@Query(value = "SELECT * FROM orders WHERE created_at > ?1", nativeQuery = true)List<Order> recent(Instant since);// Projection via interfacepublic interface OrderSummary { String getReference(); BigDecimal getTotal(); }@Query(value="SELECT reference, total FROM orders", nativeQuery=true)List<OrderSummary> summaries();