跪拜 Guibai
← All articles
Backend · Interview · Java

PO, DTO, VO: When Splitting Java Layers Pays Off and When It's Just Ceremony

By Rain的Java大神之路 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Mass assignment attacks and leaked fields are real production incidents, not theoretical concerns. A clear split rule, enforced at compile time with tools like MapStruct and ArchUnit, protects interfaces from database changes and keeps sensitive data inside the service layer without over-engineering.

Summary

Returning a JPA entity or MyBatis PO straight from a Controller leaks password hashes, phone numbers, and logical delete flags, and leaves write endpoints open to mass assignment attacks. This piece lays out the concrete costs of skipping the separation: sensitive field exposure, lazy-loading crashes, bidirectional serialization stack overflows, contract breakage when DB columns change, and wasted mobile bandwidth.

The decision framework is scenario-driven, not dogmatic: split when data crosses process or team boundaries, when interface fields differ from table fields, when change rhythms differ, or when security/serialization requirements differ. Small teams and internal tools can skip or simplify; external APIs, multi-end apps, and microservices must split. A middle path keeps PO independent while merging DTO and VO for simple interfaces.

For the conversion layer, MapStruct wins over BeanUtils because it generates compile-time code, fails the build on unmapped fields, and runs ~80x faster than reflection-based copying. Advanced patterns include CQRS-style SQL projections that output VOs directly, annotation-driven masking via Jackson serializers, ArchUnit rules that block PO leakage in CI, and validation groups or records for clean DTOs.

Takeaways
— PO must never leave the DAO layer: not in Controller return values, not across service calls; VO must never flow back into Service.
— Using PO as a write input lets attackers submit extra fields like role=ADMIN, triggering mass assignment privilege escalation.
— Split when data crosses a boundary, when interface fields differ from table fields, when change rhythms differ, or when security/serialization needs differ.
— Small teams (3 or fewer) can skip splitting; teams of 5 or fewer can use simple PO+VO; mid-to-large projects and multi-team collaboration require full separation.
— MapStruct generates mapping code at compile time, catches unmapped fields via unmappedTargetPolicy=ERROR, and runs about 80x faster than BeanUtils' reflection-based copy.
— BeanUtils copyProperties silently drops data when field types differ and performs shallow copies that share references.
— Money values should be stored as long cents, never double, to avoid precision loss.
— CQRS projection queries can skip PO entirely by selecting VO fields directly in SQL, saving memory and conversions for list pages.
— Annotation-based masking via a custom Jackson serializer removes mask logic from business code and centralizes it.
— ArchUnit architecture tests can block Controller dependencies on PO at CI time, catching violations before code review.
— DTO fields should only be added, never deleted or changed, for contract compatibility; mark deprecated fields with @Deprecated and add @JsonIgnoreProperties(ignoreUnknown=true) for tolerant inputs.
— The recommended middle ground: keep PO independent, merge DTO and VO for simple interfaces, but never let DTO couple to PO.
— PO→VO assembly should happen inside the Service transaction to avoid LazyInitializationException.
— One DTO per use case beats a universal DTO; validation groups (JSR-303 groups) handle create vs update differences.
— When converting multi-table aggregated data, use a dedicated Assembler class instead of stuffing logic into the converter.
Conclusions

Change frequency is the real driver: PO changes with DB schema, DTO with interface contracts, VO with UI updates. When those rhythms diverge, merging the objects couples unrelated teams.

The strongest argument for splitting is security, not architecture. A whitelist VO is a syntactic guarantee that sensitive fields cannot leak, which review processes alone rarely enforce.

Rejecting BeanUtils is not just about performance; reflection-based copying hides mapping errors until runtime, turning refactoring into a debugging session.

The article's pragmatic stance, allowing simple projects to skip splitting, is more useful than dogmatic layering advice. The decision tree based on boundary crossing and change rhythm gives teams a measurable rule.

CI-enforced rules like ArchUnit shift the burden from human memory to automated gates, which is the only way to keep architecture rules alive in a fast-moving team.

Concepts & terms
Mass Assignment
A security vulnerability where an attacker adds extra fields to a request payload (e.g., role=ADMIN) and the framework silently binds them to an entity, enabling privilege escalation.
PO (Persistent Object)
An object that maps one-to-one to a database table, including internal fields like password hashes and logical delete flags. It must never leave the DAO/Repository layer.
DTO (Data Transfer Object)
An object used to carry data across service or architectural boundaries. It acts as an anti-corruption layer, decoupling internal models from external contracts.
VO (View Object)
An object tailored to the frontend or presentation layer. It handles masking, formatting, enum translation, and only exposes whitelisted fields.
Anti-Corruption Layer
A protective boundary that translates between a domain model and an external model (e.g., another service's DTO), preventing internal complexity from leaking and changes from propagating.
CQRS projection
In the CQRS pattern, read queries can project only the fields needed for a view directly from the database, skipping the full entity and conversion steps. Here, SQL directly constructs a VO.
ArchUnit
A Java library that tests architecture rules, such as forbidding certain package dependencies or method return types, and can be integrated into CI to enforce layering at build time.
From the discussion

The discussion splits between those who see the PO/DTO/VO split as essential for safety and contractual clarity and those who find it divorced from real-world chaos where developers collapse everything into Maps or plain XML. Several practices surface: VO for output, Entity mapped to the table, Form for input/query, DTO as an anti-corruption layer for third-party calls. The thread also raises the shift in habits under AI-era tooling, and one reply notes that standards only work when the team respects role boundaries, not naming conventions.

— Real-world practice often abandons the layered split entirely, favoring a single Map or a single entity class across all contexts.
— The split remains valuable when it enforces boundaries: VO for responses, Form for input/query, Entity for persistence, DTO as an anti-corruption layer for external APIs.
— One developer expressed regret over pursuing strict layering early in their career, arguing AI has changed programming rules and made such boilerplate less relevant.
— A reply counters that understanding the why behind the different class types still matters, even if tooling changes.
— The idea of '和光同尘'—adapting to the team's existing style rather than forcing your own—emerges as a pragmatic counterweight to standardization.
— Naming consistency is less important than clear responsibility boundaries within a team; the split works when roles are well defined.
Featured comments
Meta 1 likes

The theory is nice, but in practice it's just all-in one go.

Rain的Java大神之路

Yes, exactly. [crying emoji]

陈佳讯 1 likes

What a waste of ambition. Three years ago, when I first started working, I pursued standard, standardized development, worked hard to learn all these different entity classes (VO, QO, DTO), MapStruct... Now that the AI era is here, programming rules have changed too.

Rain的Java大神之路

Learned something new; it's still useful. Only knowing the 'what' lets you understand the 'why'.

随风潜入月 1 likes

At my previous company, the tech lead was young and liked standardized code, so everything was split into DO, DTO, VO, and Query classes. At my current company, it's a bunch of old-timers. The whole project uses Maps for everything. The API has to be documented. The only DO and VO I wrote were by me. The classic thing is everything is in XML, nobody knows how to use MyBatis-Plus.

Rain的Java大神之路

There's a saying: 'To blend with the world's dust'—yeah, that fits.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗