Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Should a Spring service annotate its domain classes directly with JPA annotations, or keep a separate persistence model and map between them? Discuss the trade-offs and when you would choose each.

Annotating domain classes directly with JPA is less code and is the pragmatic choice when the domain fits what JPA needs. But JPA asks for things a pure domain model may not want, such as a no-argument constructor, mutable fields and proxies for lazy loading, so a separate persistence model keeps the domain clean at the cost of mapping code and duplicated structure. I choose a separate model when the domain and the schema differ a lot, when several stores are involved or when the domain is complex, and in both cases I keep repository interfaces in domain terms so callers do not depend on the choice.

Why this question is asked

Every team that takes DDD seriously in a Spring application reaches this question, often in a heated design review. One side says that @Entity on a domain class is a leak of infrastructure into the domain; the other says that a second set of classes and mappers doubles the work for no visible gain. Interviewers ask it to see whether we can weigh the trade-off honestly instead of following a rule. In this answer, we will look at the direct approach and what JPA demands of our classes, then the separate model and what it costs, then the situations that favour each, and finally how to keep the decision reversible.

1Option 1: JPA Annotations on the Domain Classes

In the direct approach, the aggregate root and its inner entities are themselves JPA entities. The domain class carries @Entity, @Id, @Embedded and @OneToMany, and the same object holds business methods and is loaded and saved by Hibernate.

Java
@Entity
@Table(name = "orders")
public class Order {
@Id private UUID id;
@Version private long version;
@Enumerated(EnumType.STRING) private OrderStatus status;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderLine> lines = new ArrayList<>();
protected Order() { } // required by JPA, hidden from the domain
public Order(UUID id) { this.id = id; this.status = OrderStatus.OPEN; }
public void addLine(ProductId p, int qty, Money price) { /* checks rules */ }
}

This is a single class, there is no mapping code, and the dirty checking of JPA saves changes automatically at commit. For many services, especially those where the domain is mostly about storing and validating data, this is the right amount of design. Notice that we can still keep the class fairly clean: the no-argument constructor is protected, fields are private with field access, and the public API is business methods rather than setters.

2What JPA Asks of a Domain Class

JPA does impose a few requirements, and they are where the friction comes from. An entity needs a no-argument constructor, public or protected, so the provider can instantiate it. Its persistent fields cannot be final, because Hibernate sets them after construction, which makes true immutability impossible for entities. For lazy loading, Hibernate creates proxies, runtime subclasses of our entity, so the class and its methods should not be final, and getClass() on a reference can return the proxy class.

There are subtler effects too. Collections are replaced by Hibernate's own persistent collections. Lazy associations can throw LazyInitializationException when touched outside a transaction. Value objects must fit @Embeddable or an AttributeConverter. And the shape of the class tends to follow the shape of the tables, because mapping a domain structure that differs from the schema requires annotations that get complicated quickly. None of this is dramatic, but each item pulls the domain model a little towards the database.

What JPA needs versus what a pure domain model wants
JPA requirementPure domain preferenceTypical workaround
No-argument constructorOnly valid constructorsMake it protected
Non-final persistent fieldsImmutable statePrivate fields, no setters
Non-final class for proxiesFinal classesAccept non-final
Persistent collectionsPlain lists or setsReturn copies from getters
Structure close to tablesStructure that fits the domainEmbeddables, converters, or a separate model

3Option 2: A Separate Persistence Model

In the separate approach, the domain classes are plain Java with no persistence annotations. A second set of classes, often named OrderJpaEntity or OrderRecord, mirrors the tables, and a mapper converts between them inside the repository implementation.

Java
// Domain: plain Java, immutable where it wants to be
public final class Order {
private final OrderId id; private final List<OrderLine> lines; private final OrderStatus status;
// business methods return new state or change it through controlled methods
}
// Infrastructure: shaped like the tables
@Entity @Table(name = "orders")
class OrderJpaEntity { @Id UUID id; @Version long version; String status; @OneToMany(...) List<OrderLineJpaEntity> lines; }
// The repository adapter maps both ways
class JpaOrderRepository implements OrderRepository {
public Optional<Order> findById(OrderId id) { return jpa.findById(id.value()).map(mapper::toDomain); }
public void save(Order order) { jpa.save(mapper.toEntity(order, existingVersion(order))); }
}

The domain is now completely free of persistence concerns: classes can be final, fields can be final, constructors can enforce every rule, and the structure can be whatever the business needs. The costs are real, though. We write and test mapping code for every aggregate, the structure is duplicated, and we lose some JPA conveniences. Dirty checking no longer sees domain changes, so we save explicitly; the version must be carried across the mapping; and lazy loading cannot be used through the domain object. Tools like MapStruct reduce the typing but not the thinking.

4When to Choose Each

I choose the direct approach by default when the domain is moderate, the tables are a close match for the aggregates, and one relational database is used. It gives most of the benefit of DDD, rich aggregates with business methods and invariants, at the lowest cost.

I move to a separate persistence model in three situations. The first is when the domain and the schema differ a lot, for example a legacy schema we cannot change, or an aggregate whose parts are spread over many tables with odd keys. Bending the domain to that schema would make it unreadable. The second is when more than one store is involved, such as part of the aggregate in PostgreSQL and part in a document store, or a migration from one database to another; JPA annotations would describe only one of them. The third is when the domain is complex enough that immutability and strict constructors materially reduce bugs, such as pricing or financial rules.

Step throughChoosing the persistence approach
  1. Do aggregates map closely to the tables?
    YesConsider direct JPA annotationsNoLean to a separate model
  2. More than one store, or a schema we cannot change?
    YesSeparate persistence modelNoContinue
  3. Is the domain complex enough to need immutability?pricing, money, rules engines
    YesSeparate persistence modelNoDirect JPA annotations

3 steps in order. Play them, or step through them one at a time.

5Keeping the Decision Reversible

Whichever we choose, the repository interface should be written in domain terms: OrderRepository with findById(OrderId) and save(Order), living in the domain layer. Services and controllers depend on that interface and on the domain classes, never on JPA types such as EntityManager or JpaRepository methods.

The reason is that this makes the choice cheap to change later. A service that started with annotated domain classes can introduce a separate persistence model for one aggregate when it becomes complex, and only that aggregate's repository implementation changes. Without the domain-shaped interface, that change would ripple through every service that called saveAndFlush or relied on lazy associations.

6Follow-up questions

Does the separate model hurt performance?

Mapping itself costs little compared with database round trips. The bigger risk is losing fetch control: if the mapper converts every association, we may load more than needed. Mapping per use case and loading exactly the aggregate solves that.

Can records be used in either approach?

Records cannot be JPA entities, because entities need mutable, non-final fields and a no-argument constructor. They can be embeddables in Hibernate 6.2 and later, and in the separate approach the whole domain model, including roots, can use records or final classes freely.

How do you handle optimistic locking with a separate model?

Carry the version in the domain object as an opaque field, or keep it in the repository adapter keyed by aggregate id for the duration of the unit of work. On save, the adapter sets the version on the JPA entity so that Hibernate's version check still runs.

7Conclusion

In this answer, we compared annotating domain classes directly with JPA against keeping a separate persistence model. Direct annotations are less code and pragmatic when the domain fits JPA, but JPA requires a no-argument constructor, mutable fields and proxies for lazy loading, which conflict with a pure domain model. A separate model keeps the domain free of persistence concerns at the cost of mapping code and duplicated structure, and it is worth it when domain and schema differ a lot, when multiple stores are used or when the domain is complex. In both cases, repository interfaces in domain terms keep callers independent of the choice.

What to say in the interviewAbout 90 seconds aloud

Open with

I treat it as a trade-off rather than a rule. Putting JPA annotations straight on the domain classes is less code, gives me dirty checking and lazy loading for free, and is the pragmatic default when the aggregates map closely to the tables and I have one relational database.

Then, if they want more

I can keep it fairly clean with a protected no-argument constructor, private fields, no setters and business methods. But JPA does push on the model: it needs that no-argument constructor, persistent fields cannot be final, classes should not be final because of proxies, collections become Hibernate collections, and the class tends to follow the table structure.

A separate persistence model removes all of that. The domain is plain Java with final fields and strict constructors, and the repository adapter maps to JPA entities shaped like the tables. The price is mapping code for every aggregate, duplicated structure, saving explicitly and carrying the version across.

I switch to the separate model when the domain and the schema differ a lot, for example a legacy schema, when more than one store is involved, or when the domain is complex enough that immutability really pays off.

Either way, I define the repository interface in domain terms in the domain layer, so callers never depend on JPA, and I can change the approach for one aggregate later without touching the rest.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Should a Spring service annotate its domain classes directly with JPA annotations, or...": https://scrivio-interview-library.netlify.app/java/domain-driven-design/54a3548520/