Friday, July 2, 2021

Using MapStruct to Simplify JPA Relationship Mapping


Context

Using MapStruct with JPA (and Living with LAZY Loading)

Separating domain models from JPA entities keeps business logic clean and independent. Domain objects stay free of persistence concerns, while entities focus strictly on database structure and behavior.

To bridge both, MapStruct generates the mapping code and removes most of the boilerplate.


The Reality: LAZY Loading

Most relationships are LAZIER by default. That’s good for performance, but it affects how mapping behaves:

  • Accessing a relation during mapping may trigger queries
  • Mapping outside a transaction can fail
  • Deep mappings can introduce hidden performance issues

At that point, mapping is no longer just conversion—it depends on how data is loaded.


What Actually Works

A few practical habits make this approach reliable:

  • Load what you need first
    Don’t let mapping drive database access
  • Keep mappings focused
    Map only what the use case requires
  • Control transaction boundaries
    Map inside a transaction or ensure data is initialized
  • Handle relationships explicitly
    Especially when mapping back to entities

A Key Advantage of This Setup

Because persistence is isolated in the entity layer, you gain flexibility:

  • You can use JPA-specific optimizations freely (fetch strategies, entity graphs, custom queries)
  • You can shape entities to match database needs without polluting the domain
  • Persistence complexity stays contained in one place

This separation lets you be pragmatic on the persistence side while keeping the domain clean.


Why It’s Still Worth It

  • Clean, testable domain
  • Minimal mapping boilerplate
  • Explicit and controlled data access
  • Freedom to optimize persistence without impacting business logic

Bottom Line

LAZY loading fits well with this architecture, but it requires discipline.

The upside is control:
You decide how data is fetched, how relationships are handled, and where persistence complexity lives.

If mapping starts requiring full object graphs, it’s usually a sign to rethink the approach—projections or read models may be a better fit.



No comments:

Post a Comment