Lesson 9 of 12 · 11 min · Data access with Spring Data JPA
JPA entities and relationships with Hibernate
What you will learn
- What JPA, Hibernate and Spring Data JPA are, and how they relate
- Map a class to a table with
@Entity,@Idand@Column - Map enums, dates and money correctly
- Model relationships:
@ManyToOne,@OneToMany(mappedBy),@ManyToMany - Cascades, orphan removal, schema migrations and
equalsfor entities
In simple words
Databases store rows in tables; Java programs work with objects. An object-relational mapper (ORM) is a translator between the two: you describe how a Java class matches a table, and the ORM writes the SQL to save and load the objects. JPA is the standard way of describing that mapping, Hibernate is the library that does the work, and Spring Data JPA saves you from writing the common queries yourself.
Words to know
- ORM: object-relational mapping, translating between objects and tables.
- Entity: a Java class mapped to a database table.
- JPA: Jakarta Persistence, the standard API for ORM in Java.
- Persistence context: the in-memory workspace where Hibernate tracks the entities it has loaded.
The three layers
| Piece | Role |
|---|---|
| JPA (Jakarta Persistence) | the specification: annotations such as @Entity and the EntityManager API |
| Hibernate ORM | the implementation Spring Boot uses by default (Hibernate 7.x in Boot 4) |
| Spring Data JPA | repositories on top: JpaRepository, derived queries, pagination (next lesson) |
Add spring-boot-starter-data-jpa and a database driver (for example PostgreSQL):
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.open-in-view=false
Boot configures a HikariCP connection pool, Hibernate and a transaction manager. In Boot 4 the JPA test slice is @DataJpaTest in org.springframework.boot.data.jpa.test.autoconfigure.
Mapping a class to a table
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 80)
private String name;
@Column(nullable = false, unique = true)
private String email;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Segment segment; // enum
private LocalDate signupDate;
protected Customer() {} // required by JPA (can be protected)
public Customer(String name, String email, Segment segment) {
this.name = name;
this.email = email;
this.segment = segment;
this.signupDate = LocalDate.now();
}
// getters; setters only where needed
}
Key points:
@Entitymarks the class; it needs a no-argument constructor (protected is fine) and a non-final class and fields (Hibernate creates proxies by subclassing). Records cannot be entities.@Idis the primary key.@GeneratedValue(IDENTITY)uses the database's auto-increment (MySQL, PostgreSQLidentitycolumns);SEQUENCEuses a database sequence (the PostgreSQL default style, and allows JDBC batching); avoidAUTOsurprises by choosing explicitly. A UUID key:@GeneratedValue(strategy = GenerationType.UUID).@Columncontrols name,nullable,length,unique. Spring's naming strategy convertssignupDatetosignup_date.- Enums: use
@Enumerated(EnumType.STRING). The defaultORDINALstores 0, 1, 2 and silently corrupts data when someone reorders the enum. - Dates:
LocalDate,LocalDateTime,Instantwork directly. PreferInstantorOffsetDateTimefor timestamps. Mark audit fields with@CreatedDateand@LastModifiedDate(with@EnableJpaAuditing). - Money: use
BigDecimalwith@Column(precision = 12, scale = 2), neverdouble. @Transientexcludes a field;@Lobfor large objects;@Versionadds optimistic locking (below).- Hibernate reads fields when
@Idis on a field (the usual style).
Schema and migrations
spring.jpa.hibernate.ddl-auto controls what Hibernate does to the schema at startup: none, validate (check the schema matches), update, create, create-drop. Do not use update in production: it cannot rename or drop columns safely and gives you no history. The professional way is versioned migrations with Flyway or Liquibase (spring-boot-starter-flyway in Boot 4): SQL files such as V1__create_customers.sql run in order and are recorded. Set ddl-auto=validate so Hibernate checks your entities against the migrated schema. For learning and tests, create-drop with an embedded H2 database is fine.
Relationships
Many-to-one (many orders belong to one customer) is the most common relationship; the table with the foreign key owns it:
@Entity
@Table(name = "orders")
public class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id") // the foreign key column in orders
private Customer customer;
@Column(nullable = false, precision = 12, scale = 2) private BigDecimal amount;
@Enumerated(EnumType.STRING) private OrderStatus status;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderLine> lines = new ArrayList<>();
public void addLine(OrderLine line) { // keep both sides in sync
lines.add(line);
line.setOrder(this);
}
}
One-to-many is usually the inverse side of a many-to-one: mappedBy = "order" says "the order field in OrderLine owns this relationship"; there is no extra column or table. Rules that avoid pain:
- Prefer unidirectional
@ManyToOnewhere you can; add the@OneToManyside only if you need to navigate from the parent. - For a bidirectional link, update both sides with a helper method (
addLine), because only the owning side (@ManyToOne) writes to the database. - Set
fetch = LAZYon@ManyToOne(its default is EAGER, which causes surprising extra queries; the next lesson explains).@OneToManyis lazy by default. - A
@OneToManywithoutmappedBycreates an extra join table; rarely what you want.
Cascade passes operations from parent to children: cascade = CascadeType.ALL means saving or deleting an Order also saves or deletes its lines. Use it for true parent-child compositions (order and order lines), never from OrderLine to Customer or between independent aggregates. orphanRemoval = true deletes a child removed from the parent's collection.
One-to-one: @OneToOne (often with a shared primary key via @MapsId).
Many-to-many (students and courses): either a @ManyToMany with @JoinTable, or, better, an explicit join entity (Enrollment with its own fields such as enrolledOn), because real relationships soon need extra data:
@Entity
class Enrollment {
@EmbeddedId private EnrollmentId id;
@ManyToOne @MapsId("studentId") private Student student;
@ManyToOne @MapsId("courseId") private Course course;
private LocalDate enrolledOn;
}
Embeddables (@Embeddable/@Embedded) group value fields such as an Address into the same table. Inheritance (@Inheritance) exists but use it sparingly.
equals, hashCode and toString for entities
Entities need care (building on the Core Java lesson):
- The database id is
nulluntil the entity is saved, so an id-basedhashCodechanges atpersist. A pragmatic pattern:equalscompares the id only if non-null (and the same class, usingHibernate.getClassfor proxies), andhashCodereturns a constant per class (getClass().hashCode()). Or use a stable business key (email, order number). - Never include lazy collections or back-references in
toString,equalsorhashCode: they trigger queries or infinite recursion in bidirectional links. - Do not use Lombok
@Dataon entities. - Do not return entities from controllers; use DTOs.
Optimistic locking
Two people editing the same row at once can overwrite each other. Add a version column:
@Version
private Long version;
Hibernate adds WHERE version = ? to updates and throws ObjectOptimisticLockingFailureException if someone else changed the row first; map it to 409 Conflict. Use pessimistic locks (@Lock(PESSIMISTIC_WRITE)) only for hot rows where conflicts are likely.
Common mistakes
EnumType.ORDINAL.FetchType.EAGERon associations and loading half the database.- Bidirectional relationships with only one side updated, or cascades from child to independent parent.
ddl-auto=updatein production.doublefor money.@Dataon entities and relationship fields intoString.- Exposing entities in the API.
Try it yourself
- Create
CustomerandOrderentities with a lazy@ManyToOne, run against H2 withddl-auto=create-drop, and read the generated SQL (spring.jpa.show-sql=true). - Add
OrderLinewith@OneToMany(mappedBy, cascade = ALL, orphanRemoval = true)and a helper method; save an order with two lines and check the three inserts. - Replace
ddl-autowith a Flyway migration andvalidate. - Add
@Versionand simulate two conflicting updates in a test.
Check yourself
What is the relationship between JPA, Hibernate and Spring Data JPA?
JPA is the standard specification, Hibernate is the implementation Spring Boot uses, and Spring Data JPA builds repositories on top so you rarely write queries by hand.
Why use @Enumerated(EnumType.STRING)?
The default ordinal storage depends on the enum order, so reordering or inserting constants silently corrupts existing data; strings are stable.
What does mappedBy mean?
It marks the inverse side of a bidirectional relationship and names the field on the owning side that holds the foreign key, so no extra column or table is created.
When should you use cascade and orphanRemoval?
For true parent-child compositions, such as an order and its lines, where children cannot exist without the parent.
Interview questions
Explain the difference between @OneToMany with and without mappedBy.
With mappedBy it is the inverse side of a @ManyToOne and uses that foreign key. Without it, Hibernate creates a separate join table, which is usually unintended and less efficient.
What are the entity states in JPA?
New (transient, not tracked), managed (tracked in the persistence context, changes flushed automatically), detached (was managed, session closed) and removed (scheduled for deletion).
Why not use ddl-auto=update in production?
It applies unreviewed, irreversible changes, cannot handle renames or drops, and gives no history; use Flyway or Liquibase migrations and validate.
Summary
- JPA is the standard, Hibernate the implementation, Spring Data JPA the convenience layer.
- Map entities with
@Entity,@Id,@Column; use string enums,BigDecimalandjava.time. - Prefer lazy
@ManyToOne,mappedByon the inverse side, and cascade only on real compositions. - Use migrations (not
ddl-auto=update), optimistic locking and carefulequals/toString.
Going deeper
- Spring Data JPA reference: entities, repositories and queries.
- Spring Boot: SQL databases: data sources, JPA and migrations.
- Hibernate ORM documentation: the user guide for mappings and relationships.
- Jakarta Persistence specification: the standard annotations and API.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.