跪拜 Guibai
← Back to the summary

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

During code review, a newcomer returned UserPO directly to the frontend, and passwords and a logical delete flag were exposed. I said we needed to split PO, DTO, and VO; another colleague countered: isn't this over-engineering? You've surely seen this scene. Today we'll explain this debate once and for all: what to split, when not to split, and how to split without writing a pile of get/set methods.

First, know the whole "xO" family: everyone has their own boss

Much of the debate stems from conceptual confusion. These Java backend "O"s each have their own territory. Look at the family portrait first:

Object Full name Layer Core responsibility Change frequency Common annotations
PO Persistent Object DAO / Repository Maps one-to-one to database tables, includes internal fields like passwords and delete flags Low, DB is stable @TableName @Entity
BO Business Object Service Business composite aggregating multiple tables, carries business logic Medium @Builder
DO Domain Object Service / Domain Domain model in DDD, has business behavior Medium @Data
DTO Data Transfer Object Cross-service / cross-layer transmission Business data transfer, can aggregate multiple tables, trim sensitive fields Medium @Valid
VO View Object Controller → Frontend Display-specific: formatting, masking, enum-to-text High, frontend changes daily @JsonInclude @JsonFormat
Command / Query — Controller input Write operation inputs / query conditions, carry validation rules High @Valid @NotBlank

One-sentence memory aid:

PO is what the database sees, BO is what the business sees, DTO is what's in the delivery package, VO is what the front desk sees.

Also note a key detail: each object has a different "boss", and changes are driven by different people: PO changes because the DBA changes the table, DTO changes because of interface contract review, VO changes because the product changes the UI. Different bosses and different change rhythms mean they should be managed separately.

So these three objects can also be understood as three firewalls: database table changes are isolated by PO, service contract changes are isolated by DTO, and page field changes are isolated by VO.

From the perspective of change frequency, the whole chain looks like this:

image.png

The further inward, the more stable; the further outward, the more changeable. So the fundamental meaning of layering is eight characters: stable inside, changeable outside, dependencies must be one-way. Outer layers depend on inner layers; inner layers never know about outer layers. This is dependency inversion.

The full data flow panorama:

image.png

Split into two lines for easier memory:

Here's an iron rule worth engraving into DNA:

PO must never leave the DAO layer, neither in a Controller return value nor directly for cross-service transmission; VO must never flow back into the Service layer. Each layer's objects only operate within their own responsibility scope.

A quick clarification on terminology: strictly speaking, DTO is the broad "transfer object", and both request parameters (Req) and response parameters (Resp) count as DTO. Many teams habitually call inputs DTO and outputs VO; essentially, that's just giving a direction a name. Don't nitpick terms; look at responsibilities.

Also don't memorize rigid formulas like "Controller uses VO, Service uses DTO, DAO uses PO". Real projects divide by responsibility, not by layer filling.

At this point you might ask: they're all just data carriers, why split so many? Don't worry, let's first see what happens if you don't split.

Why split: all blood and tears lessons

Counterexample: one PO for everything

Many incidents start with a code shortcut:

@GetMapping("/{id}")
public UserPO getUser(@PathVariable Long id) {
    return userMapper.selectById(id);   // shortcut, return PO directly
}

Open F12 and take a look:

{
  "id": 1,
  "username": "qwen",
  "password": "$2a$10$xxxx",
  "phone": "13800000000",
  "status": 1,
  "deleted": 0,
  "createTime": "2026-11-02"
}

Password hash, phone number, logical delete flag: all exposed. If the query endpoint is like this, the write endpoint receiving PO directly is even more exciting:

// Counterexample: using PO directly to receive frontend parameters
@PostMapping("/user")
public void create(UserPO user) { ... }

An attacker submits with an extra field: {"username":"hacker","role":"ADMIN"}, and the ORM faithfully binds all fields, making privilege escalation succeed directly. This is the classic Mass Assignment (parameter override attack), security-incident level.

These incidents have actually happened

Besides leakage, here are real pitfalls seen in production:

Incident On-site manifestation Severity
Sensitive field leakage password, salt, idCard returned as-is to frontend P0
Bidirectional association infinite loop Jackson serialization A→B→A, directly StackOverflowError, early-morning alerts P1
Lazy loading explosion Controller touches ORM lazy-loading collection, with open-in-view off it throws LazyInitializationException P1
Contract hijacked by database tables DBA changes a column name, frontend interface breaks P1
Bandwidth waste Table has 20 fields, interface uses only 5, JSON bloats, mobile traffic wasted P2
Semantic confusion Validation like "id cannot be empty on update" written everywhere, inconsistently P2
Hard to test Unit tests need a giant all-field object P3

Splitting actually splits these four things

After seeing the pitfalls, let's talk about what splitting solves.

1. Change isolation: split by change frequency, not field count

In real development you often hit this: the product says "add an email field to the user list". Without splitting, you change the table → add a field to PO → all interfaces using PO undergo contract changes, and documents need re-issuing. With splitting, only VO and SQL change, other interfaces stay untouched. Database table changes don't pull in interfaces, page redesigns don't drag table structures. That's the core value of layering.

2. Security boundary: the hardest reason

Each layer only takes the minimal data set it needs, preventing sensitive fields from crossing boundaries at the syntax level. The VO whitelist is the last security gate.

3. Contract/implementation separation: DTO is an anti-corruption layer

External API is a contract, entities are internal implementation. Contracts must be stable, implementations must be refactorable at any time; mixing them is like "redoing the contract just to change the decoration". In microservices, if service A's UserDTO contract stays unchanged, no matter how A's internal table structures change, the calling service B is unaware. That's the biggest meaning of DTO: the Anti-Corruption Layer, blocking the complexity of internal models at the service boundary.

4. Multi-end adaptation and team collaboration

The same business data: PC needs full information, APP needs trimmed fields, admin backend needs audit fields. Just define different VOs, and the underlying business logic is fully reused. After standardizing layering, DBA, backend, and frontend can develop in parallel, aligning only through DTO/VO interface contracts. Newcomers know an object's role boundary just by its class name; layered naming is the best self-documentation.

Benefit comparison:

Dimension Not split Split
Security Full field exposure On-demand exposure, sensitive fields naturally isolated
Evolution DB field change → frontend breaks Layers evolve independently
Volume Transmission redundancy Precise slimming
Semantics Validation and display mixed together Each does its own job
Testing Painful data creation Easy mocking

The essence of entity layering: trade a small amount of code redundancy for architectural decoupling, security boundaries, and evolution freedom.

Reasons done. A new question arises: do all projects need this split? Of course not.

Split or not: look at the scenario, not faith

Conclusion first: whether to split is not a faith issue, it's a scenario issue. There's no silver bullet, but there are clear judgment lines.

These scenarios must split

Scenario Reason
External RPC / OpenAPI contract DTO is the contract; adding a DB field must not break someone else's service
Write interfaces with input containing id / status / audit fields Directly receiving PO makes you a living target for parameter override; must split XxxCreateDTO / XxxUpdateDTO
Tables contain passwords / phone numbers / logical delete / internal status VO does trimming and masking, guarding security
Frontend-required fields ≠ table fields Concatenation, translation, formatting, enum-to-text: VO carries display logic
Microservice cross-service calls Anti-corruption layer, prevents domain model leakage and version coupling
Multi-end reuse (PC / APP / mini-program / admin) Shared DTO, each end customizes its own VO
Permission-based field control Regular users and admins see different fields
Interface version compatibility needed Isolate database changes from interface changes
Complex aggregate pages Multi-table, multi-service data assembly

These scenarios can be lazy

Scenario Suggestion Explanation
Personal projects / startup MVP / prototype validation Don't split Speed to launch beats architectural elegance
Internal small tools, one-off scripts Don't split Efficiency first
Single-table CRUD, read-only lists, fields 1:1 with table and no sensitive fields Can output directly Add @JsonIgnore as safety net, leave comments for future split
Small team (under 5 people) simple business Simple split PO + VO two steps enough

Rough reference by team size: 3 or fewer people, don't split; under 5, simple split; mid-to-large projects and multi-team collaboration, must split.

The compromise for most teams

PO must be independent; DTO and VO merge as needed.

Simple interfaces: DTO returned directly as VO, saving one meaningless conversion; complex interfaces: define a separate VO for renaming, formatting, trimming.

Two ugly truths up front:

If still unsure, four hard criteria: if any one hits, split:

  1. Crosses boundary (through gateway, across processes, across teams);
  2. Field set differs (interface fields ≠ database table fields);
  3. Evolution rhythm differs (table field changes ≠ interface field changes);
  4. Security / serialization style differs (masking, format, compatibility requirements).

Or just look at this decision tree:

image.png

Finally, add a big-company baseline and a red line:

PO should never appear in a Controller return value. Even for admin backend, at least convert to VO once.

Internal tools allow PO direct output, but as soon as it goes through the gateway, as soon as it's given to an external team, add VO that same day; don't wait for an incident to backfill.

Scenarios are clear. Now for implementation. The following code can be copied directly into your project; bookmark it first.

Standard posture: reusable code

PO: only talks to the database

Don't add any "show to frontend" responsibility to PO:

@Data
@TableName("t_user")
public class UserPO {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    @TableField(select = false)          // password not in regular queries
    private String passwordHash;
    private String salt;
    private String phone;
    private Integer status;              // 0 disabled 1 enabled
    @TableLogic
    private Integer deleted;             // logical delete flag; seeing it in output is an incident
    private Long balanceCent;            // money always in "cents", reject double
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
}

Several details worth noting:

DTO: secure gate for inputs

One use case, one object; validation rules follow the object:

@Data
public class UserCreateDTO {

    @NotBlank(message = "username cannot be blank")
    @Size(min = 4, max = 20, message = "username length 4-20")
    private String username;

    @NotBlank(message = "password cannot be blank")
    @Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,20}$",
             message = "password must contain upper/lowercase letters and digits, 8-20 chars")
    private String password;

    @NotBlank(message = "phone cannot be blank")
    @Pattern(regexp = "^1[3-9]\\d{9}$", message = "invalid phone format")
    private String phone;

    @Email(message = "invalid email format")
    private String email;
}

Two practical lessons:

First, don't create a universal DTO. If one DTO is reused across 10 interfaces, adding a field affects all. The create use case goes through the Create validation group, update through the Update group (JSR-303 groups). Better to write more classes than to couple.

Second, teams on Java 17+ can use record directly:

public record UserCreateDTO(
    @NotBlank(groups = Create.class) @Size(max = 32) String username,
    @NotBlank @Pattern(regexp = "^1[3-9]\\d{9}$") String phone,
    @NotBlank(groups = Create.class) String password
) {}
public interface Create {}   // update use case separately defines Update group

Naturally immutable, no setter pollution; MapStruct 1.5+ natively supports record constructors.

VO: frontend can only see these

@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)  // null fields not returned, saves bandwidth
public class UserVO {
    private Long userId;        // field renamed to match frontend naming convention
    private String userName;
    private String phoneMask;   // masked: 138****8000
    private String statusDesc;  // enum translation: enabled / disabled, not raw 0/1
    private String createTime;  // formatted: yyyy-MM-dd HH:mm, not raw Instant
    // no passwordHash, salt, deleted
}

The design philosophy of VO is a whitelist: default is to expose nothing, only declare what to expose. Display logic like enum-to-text and time formatting shouldn't be left for the frontend or pollute the Service; the conversion layer is the right place — details later.

Full chain: Controller / Service / Mapper

See the write path (registration) and read path (query) together:

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/{id}")
    public Result<UserVO> getUser(@PathVariable Long id) {
        UserDTO userDTO = userService.getUserById(id);
        UserVO userVO = UserConverter.INSTANCE.toVO(userDTO);
        return Result.success(userVO);
    }

    @PostMapping("/register")
    public Result<UserVO> register(@Valid @RequestBody UserCreateDTO dto) {
        return Result.success(userService.register(dto));
    }
}
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public UserDTO getUserById(Long id) {
        UserPO userPO = userMapper.selectById(id);
        if (userPO == null) {
            throw new BusinessException("user not found");
        }
        // business validation, permission check, field filtering all here
        return UserConverter.INSTANCE.toDTO(userPO);
    }

    @Override
    public UserVO register(UserCreateDTO dto) {
        UserPO po = UserConverter.INSTANCE.toPO(dto);
        // password encryption only in Service layer, Controller never touches it
        po.setPasswordHash(passwordEncoder.encode(dto.getPassword()));
        userMapper.insert(po);
        // return after masking
        return UserConverter.INSTANCE.poToVo(po);
    }
}
@Mapper
public interface UserMapper extends BaseMapper<UserPO> {
}

After layering, code gets amazingly clean: Controller doesn't touch password encryption, Service doesn't care about masking. To change return fields, only VO and converter change.

One pitfall worth emphasizing: PO → VO assembly should happen inside the Service transaction, don't let Controller touch the ORM Session, otherwise lazy loading blows up.

Code is written, but a new problem appears: the conversion code among PO, DTO, and VO is not trivial. This is the dividing line between junior and senior.

The conversion layer is the watershed: BeanUtils or MapStruct

The biggest pain of splitting is object conversion. There are three schools in the industry:

Solution Performance Type safety Compile-time check Conclusion
Handwritten get/set Fastest (~10ns/op) Safe Safe OK for few fields, painful for many
BeanUtils.copyProperties Slow (~1200ns/op, reflection) Unsafe Only errors at runtime Not recommended
MapStruct Close to handwritten (~15ns/op) Safe Compile-time errors Big companies' first choice

(The ns data are per-call order-of-magnitude references; versions vary, but reflection vs compile-time generation differs by about 80x — a order-of-magnitude gap.)

Why so down on BeanUtils? It's reflection + string matching:

// Pit 1: same name but different type, silently lost
class A { private Date createTime; }
class B { private String createTime; }  // BeanUtils can't copy, no error!

// Pit 2: shallow copy shares references
orderBO.setUserList(userPOList);  // modify BO's list, PO changes too!

If a field is renamed, compilation doesn't fail, data is silently lost in production, and debugging takes a day. MapStruct generates code at compile time; a mismatched field turns the build red. That's an essential difference.

MapStruct core usage

@Mapper(componentModel = "spring",
        unmappedTargetPolicy = ReportingPolicy.ERROR,   // missing mapping directly fails compilation
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        uses = MaskQualifier.class)
public interface UserConverter {

    UserConverter INSTANCE = Mappers.getMapper(UserConverter.class);

    // PO -> DTO: explicitly ignore sensitive fields
    @Mapping(target = "passwordHash", ignore = true)
    @Mapping(target = "salt", ignore = true)
    @Mapping(target = "deleted", ignore = true)
    UserDTO toDTO(UserPO po);

    // DTO -> VO: rename + mask + enum translation + time formatting
    @Mapping(source = "id", target = "userId")
    @Mapping(source = "username", target = "userName")
    @Mapping(target = "phoneMask", source = "phone", qualifiedByName = "maskPhone")
    @Mapping(target = "statusDesc",
             expression = "java(StatusEnum.descOf(dto.getStatus()))")
    @Mapping(source = "createTime", target = "createTime",
             dateFormat = "yyyy-MM-dd HH:mm")
    UserVO toVO(UserDTO dto);

    // batch conversion, list pages directly convert
    List<UserVO> toVOList(List<UserPO> poList);

    // to DB: DTO -> PO, ignore id and auto-filled fields
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "status", ignore = true)
    UserPO toPO(UserCreateDTO dto);
}

Masking logic is gathered into one Qualifier, reused across the site, unit-testable:

@Component
public class MaskQualifier {

    @Named("maskPhone")
    public String maskPhone(String phone) {
        return phone == null ? null
             : phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    @Named("maskIdCard")
    public String maskIdCard(String idCard) {
        return StrUtil.hide(idCard, 6, 14);   // 110***********1234
    }
}

Three highlights worth circling in interviews:

Highlight 1: unmappedTargetPolicy = ReportingPolicy.ERROR. Table adds a field but VO forgets to map? Build fails at compile time, no waiting for production. Being able to say this parameter means you've really stepped on pitfalls.

Highlight 2: expression and qualifiedByName fold masking and enum translation into the conversion layer. Service only cares about business; display logic doesn't pollute the domain.

Highlight 3: compile-time generation, zero reflection. The generated implementation is handwritten-level get/set, performance essentially equal, and source is readable:

// generated under target/classes, no reflection, no black box
public class UserConverterImpl implements UserConverter {
    @Override
    public UserVO toVO(UserDTO dto) {
        UserVO vo = new UserVO();
        vo.setUserId(dto.getId());
        vo.setUserName(dto.getUsername());
        vo.setPhoneMask(maskQualifier.maskPhone(dto.getPhone()));
        vo.setStatusDesc(StatusEnum.descOf(dto.getStatus()));
        // ...
        return vo;
    }
}

Complex scenarios: nesting, computation, encrypted persistence

Nested object mapping and computations during conversion: MapStruct handles them:

@Mapper(componentModel = "spring")
public interface OrderConvert {

    @Mapping(source = "user.name", target = "userName")   // nested object mapping
    @Mapping(source = "createTime", target = "createTime",
             dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(target = "totalPrice", expression = "java(calculateTotal(order))")
    OrderDetailVO toVO(OrderPO order);

    // custom calculation logic: compute total directly during conversion
    default String calculateTotal(OrderPO order) {
        int total = order.getItems().stream()
                .mapToInt(OrderItemPO::getPrice)
                .sum();
        return total + "元";
    }
}

Nested one-to-many List mappings are also supported. When persistence involves encryption, using default methods handwritten is more intuitive and controllable:

default UserPO toPO(UserCreateCmd cmd) {
    String salt = PasswordUtil.salt();
    UserPO po = new UserPO();
    po.setUsername(cmd.getUsername());
    po.setPasswordHash(PasswordUtil.hash(cmd.getPassword(), salt)); // BCrypt
    po.setSalt(salt);
    po.setStatus(1);
    po.setDeleted(0);
    return po;
}

Interview bonus: if conversion involves multi-table aggregation (order + user + product), add a dedicated Assembler layer, don't stuff it into Converter. Single responsibility; the converter isn't a utility closet.

With the conversion layer handled, splitting cost becomes very low. But since we're pursuing excellence, let's look at a few advanced plays: some double list-page performance, some remove masking from business code.

Advanced tricks: faster and more stable

Trick 1: CQRS projection direct query, list pages skip PO

The conventional approach queries full PO then converts to VO. But for list pages, dashboards, exports — read-heavy scenarios with wide tables and many fields — querying all columns then converting wastes memory and GC. A more aggressive approach: SQL directly outputs VO, only query the fields the page needs:

// JPA projection query: skip PO, directly assemble VO
@Query("select new com.xxx.vo.UserVO(u.id, u.username, u.phone, r.label) "
     + "from UserPO u join u.role r where u.status = :status")
List<UserVO> listByStatus(@Param("status") Integer status);

For MyBatis, even more thorough: masking and enum translation done directly in SQL:

@Select("""
    SELECT id            AS userId,
           username      AS userName,
           CONCAT(LEFT(phone,3), '****', RIGHT(phone,4)) AS phoneMask,
           CASE status WHEN 1 THEN '启用' ELSE '禁用' END AS statusDesc,
           DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s')  AS createTime
    FROM t_user
    WHERE deleted = 0 AND status = #{status}
""")
List<UserVO> selectUserVO(@Param("status") Integer status);

This is the CQRS idea: write path honestly goes DTO→PO, read path directly outputs VO via SQL, saving two conversions, with visible benefits for wide-table large-field scenarios. Of course, read/write separation also means maintaining two field sets; decide based on scenario.

Trick 2: annotation-based masking, zero intrusion into business code

Many projects mask like this: userVO.setPhone(maskPhone(userPO.getPhone())). With many interfaces, the code scatters everywhere. More elegant: annotation + Jackson serializer for unified governance:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sensitive {
    SensitiveType value();
}

public enum SensitiveType {
    PHONE, EMAIL, ID_CARD, BANK_CARD
}

Just annotate VO fields:

@Data
public class UserVO {
    private Long id;
    private String username;

    @Sensitive(SensitiveType.PHONE)
    private String phone;

    @Sensitive(SensitiveType.EMAIL)
    private String email;
}

The serializer detects the annotation and masks automatically:

public class SensitiveSerializer extends JsonSerializer<String>
        implements ContextualSerializer {

    private SensitiveType type;

    @Override
    public void serialize(String value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        gen.writeString(SensitiveUtil.mask(type, value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov,
                                              BeanProperty property) {
        if (property != null) {
            Sensitive sensitive = property.getAnnotation(Sensitive.class);
            if (sensitive != null) {
                SensitiveSerializer serializer = new SensitiveSerializer();
                serializer.type = sensitive.value();
                return serializer;
            }
        }
        return this;
    }
}

Output automatically becomes:

{
  "id": 1,
  "username": "qwen",
  "phone": "138****0000",
  "email": "q***@example.com"
}

Masking logic is pulled out of business code and governed centrally; new interfaces just add an annotation.

Trick 3: ArchUnit architecture guard, turning rules into compile-time red lines

Rules written in docs are unreliable; someone will forget. More reliable: turn conventions into compile-time / CI gates:

// Guard 1: Controller layer prohibited from depending on PO
@ArchTest
static final ArchRule controller_should_not_return_po =
    noClasses().that().resideInAPackage("..controller..")
        .should().dependOnClassesThat().resideInAPackage("..po..")
        .because("Controller must return VO/DTO, PO must not leak");

// Guard 2 (more precise): method return type prohibited from being PO
@ArchTest
static final ArchRule controllers_should_not_expose_po =
    noMethods()
        .that().areDeclaredInClassesThat().resideInAPackage("..controller..")
        .should().haveRawReturnType(resideInAPackage("..po.."))
        .because("Controller must not return PO directly, must convert to VO");

This beats code review a hundred times: a new teammate casually returns PO, CI goes red, never reaches production. You can also add a ResponseBodyAdvice as a final audit layer, dual insurance.

Trick 4: generics + base classes, eliminate class explosion

Worried about class explosion? Two moves:

// Move 1: generic pagination VO, one class serves 50 list interfaces
@Data
public class PageResult<T> {
    private Long total;
    private Long pages;
    private List<T> records;
    private Long current;
    private Long size;
}
// Usage: PageResult<UserVO>, PageResult<OrderVO>…… all works

Move 2: extract common fields into a base class (BasePO for id, createTime, updateTime, deleted). Lombok eliminates boilerplate. For mid-to-large admin backends, use MyBatis-Plus Generator to generate all layer entities in one go.

Trick 5: contract evolution, only add, never delete

External interfaces will inevitably face version compatibility: old App versions call new interfaces; you delete or change a field, their parsing crashes. Three rules:

Also, repeatedly defining the same DTO between microservices? Extract a common contract Module, or use Protobuf / Thrift generation to eliminate copy-paste.

Tricks done. Finally, a pitfall quick-reference table — these are bought with real gold; save every row.

Pitfall quick reference: technical difficulties and solutions

First, a high-frequency pitfall — circular references. One-to-many associations nesting each other, Jackson serialization recurses infinitely:

@Data
public class OrderVO {
    private Long userId;
    private String userName;   // only put name, not entire UserVO
    // private UserVO user;    // this would recurse and StackOverflow
}

VO one-way modeling to break the cycle beats any serialization trick. The rest are in the table:

# Difficulty Pitfall scene Solution
1 Conversion boilerplate explosion 100 entities × 3 layers = 300 classes, handwritten get/set misses fields when changed MapStruct compile-time generation + unified XxxAssembler convention
2 Class explosion, over-layering PO→DO→DTO→VO→Model five-layer chain, one query has 8 classes Split by change direction: merge same change rate, only create objects at boundaries; extract common base classes, package by module
3 Field drift, silent missing conversion DB adds field, DTO not synced, frontend can't get it unmappedTargetPolicy=ERROR + unit test asserting key fields + contract tests
4 BeanUtils hidden bomb Same name different type silently loses data, shallow copy shares references Reject runtime reflection copying; use MapStruct explicit @Mapping
5 Sensitive field leakage New teammate returns PO, password exposed PO never leaves DAO + VO whitelist + ArchUnit gate + ResponseBodyAdvice audit + code scanning
6 Circular reference infinite recursion Bidirectional association serializes into StackOverflowError VO one-way modeling breaks the cycle; @JsonBackReference / @JsonIgnoreProperties
7 Lazy loading explosion Controller touches lazy collection, LazyInitializationException spring.jpa.open-in-view=false, assembly inside Service transaction, fetch join
8 Validation rules conflict Create needs password, update doesn't, one DTO fights Validation Group + split Req by use case; validation in Command/Query + @Valid, Service only checks business rules
9 Semantic drift Money double loses precision, timezone chaos, enum raw 0/1 exposed VO explicit types: money long cents, Instant→String, enum→{code,desc}
10 DTO universalization One DTO reused across 10 interfaces, adding field affects all One interface one DTO, minimize interface fields; prefer more classes over coupling
11 Reverse conversion error-prone VO→PO reverse write-back, nested structures hard to debug Strict convention: VO read-only, write operations must use DTO; @Builder + unified logging helps
12 List page performance poor First query full PO then convert, N+1, GC pressure CQRS projection direct query + batch query / JOIN / cache
13 Microservice model coupling Service A directly uses Service B's DB entities Anti-corruption DTO, services depend only on contracts
14 Permission field control Regular users and admins see different fields Different VOs, or dynamic filtering during serialization
15 Masking logic scattered Each interface manually masks phone @Sensitive annotation + Jackson serializer unified governance
16 Should DO/BO be another layer? Layers get messier Three questions: multi-table aggregation? → need BO; independent domain model (DDD)? → need DO; simple single-table CRUD? → DTO directly to PO, don't over-design

The table is a bit long, but anyone who's hit any of these knows they're all worth it. Incidentally, this question is also a high-frequency big-company interview topic. Here's how to answer for bonus points.

Bonus: how to answer this in an interview

This question appears very frequently. A tip: candidates who can explain these four points — "change rate + security boundary + proactively mention non-split scenarios + MapStruct compile-time checks" — many interviewers mark Strong Hire directly.

Common follow-ups and response ideas:

Follow-up Reference answer points
Difference between MapStruct and BeanUtils? MapStruct compile-time generation, type-safe, an order of magnitude faster; BeanUtils runtime reflection, renames don't error, silently loses data
Can DTO and VO merge? Simple scenarios yes, but recommend separation; merging muddies responsibilities, higher maintenance cost later
What granularity does your project actually split to? Controller layer DTO+VO must split; Service layer single-table CRUD doesn't split BO, only aggregate queries split. Split follows complexity, not dogma
What naming convention does your team use? Alibaba Java Development Manual recommends layering; we use xxxPO / xxxDTO / xxxVO
Between microservices, DTO or domain object? Always DTO, avoid domain model leakage and version coupling
How to ensure conversion performance? Compile-time mapping + batch toVOList + handwritten on necessary hot paths
Can PO be used as DTO directly? Small projects yes, but once field trimming and sensitive fields are involved, must split
Isn't splitting tiring to refactor? Tiring is the "all-field triplet", not layering itself. Split by change rate: DB change only touches PO + one line in Assembler, interface change only touches VO, neither propagates, long-term it's actually the least work
Small projects? Internal admin, single-table CRUD prototypes, PO direct output is fine; but keep a red line: if it goes through the gateway or to an external team, add VO that same day

If the interviewer wants a 30-second wrap-up, use this template:

The essence of splitting is isolating change: PO for storage, DTO for use cases, VO for contract. PO is the database's mirror, contains sensitive fields, never leaves Controller; DTO is service contract, trims fields, ensures compatibility; VO for frontend pages, handles masking, formatting, text conversion; inputs use Command/Query, business uses BO/Domain. Implementation: MapStruct compile-time mapping prevents missing fields; queries use CQRS direct VO for performance. It's not about more classes — internal tools can be simple, but microservices, multi-end, external interfaces must split. Better to split early than wait until external callers depend on your salt field.

Finally, a mnemonic to memorize:

PO hugs the DB, DTO signs contracts outside,
VO smiles at the frontend, BO manages business in the middle.
Inner stable, outer jumps, dependencies one-way, don't tangle.
Not splitting is fine, but split when needed; keep boundaries.

Final words

Layering isn't showing off; it's building firebreaks for "change". Three sentences to wrap up:

A quick-reference table, use it:

Question Suggestion
Split or not? Complex systems split, simple systems can simplify
Can PO be returned to frontend directly? Not recommended
Can DTO and VO merge? Simple scenarios yes, complex scenarios no
What does Service use? DTO / BO
What does Controller return? VO / Response
What does Mapper operate on? PO
What for object conversion? MapStruct
How to handle sensitive fields? Masking annotation + serializer unified handling
Core idea? Boundary isolation, models don't cross layers

Three actionable suggestions for tomorrow:

  1. Check Controller return values in your project, convert all direct PO outputs to VO, prioritize those with sensitive fields;
  2. Introduce MapStruct, enable unmappedTargetPolicy = ReportingPolicy.ERROR;
  3. Add an ArchUnit rule to block "Controller returns PO" in CI.

A good architect knows when to introduce constraints and when to remove them. Knowing when to split and when not to split is the full-score answer. Layering isn't for ritual; it's for sleeping soundly during change.

Finally, a topic: Does your team split PO, DTO, VO? Or one entity for everything? What's the most painful pitfall you've hit in layering? Share in comments, I'll pick a few typical ones and elaborate.

If useful, thumbs up and "wow" are the biggest support; to keep seeing big-company real-world practice, follow for the next issue.

Comments

Top 5 of 9 from juejin.cn, machine-translated. The original thread is authoritative.

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.

菜鸟码农_ 1 likes

Splitting is definitely necessary. I generally use VO for the frontend response, Entity corresponds to the database table, Form for form submission and queries, and DTO for third-party API returns.

Rain的Java大神之路

Haha, nice, awesome. Entity matches PO, Form does the work of Command/Query, DTO specifically handles third-party integration as an anti-corruption layer—that's a pretty standard setup. VO for output + Form for input covers both safety and contract boundaries. So there's really no need to unify naming; as long as the team has clear responsibility boundaries, it's fine. Thanks for sharing the practice.

四十四次日落238

Very inspiring, quite in-depth.