You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dto转Entity后调用getId出现NPE问题求助(MapStruct/ModelMapper)

Troubleshooting NullPointerException When Accessing Entity ID After DTO Conversion

First, let’s break down why you might be seeing a NullPointerException (NPE) when calling model.getId()—even though model.getCreationTime() works, which confirms the model instance itself isn’t null.

Most Likely Cause: Unboxing a Null Long to Primitive long

The id field in your AbstractModel is a nullable Long wrapper type. If your DAO code tries to assign this to a primitive long variable, unboxing a null value will throw an NPE:

// This throws NPE if model.getId() returns null
long customerId = model.getId();

Fix this by using the wrapper type Long to avoid unboxing issues:

// Safe even if id is null
Long customerId = model.getId();

Or explicitly check for null before unboxing:

if (model.getId() != null) {
    long customerId = model.getId();
    // Use customerId safely
}

Other Possible Causes to Check

1. Incorrect Getter Implementation for id

Double-check that your getId() getter in AbstractModel is a standard, minimal implementation:

public Long getId() {
    return id; // No extra logic that could throw NPE
}

If the getter includes additional code (like converting to a primitive or accessing another null object), that could be the source of the error.

2. Mapper Configuration Quirks

Even though you tried ModelMapper and MapStruct, ensure your mapper isn’t accidentally setting the id field to something invalid. For new entities (like a new Customer), the id should remain null until JPA generates it on save:

  • For ModelMapper: Verify you haven’t configured a mapping that forces an unexpected value into the id field.
  • For MapStruct: Ensure your mapper interface doesn’t attempt to map a non-existent id from the DTO (MapStruct ignores missing fields by default, but custom configurations might override this).

3. Debug to Confirm the Root Cause

Add simple debug statements right before the line that throws the NPE to clarify what’s happening:

System.out.println("Model instance exists: " + (model != null));
System.out.println("Model ID value: " + model.getId());
System.out.println("Creation time value: " + model.getCreationTime());

This will confirm if model.getId() is returning null (expected for unsaved entities) or if there’s a hidden issue with the field or getter.

Remember: For new entities that haven’t been persisted yet, the id field should be null. Your code needs to handle this null case gracefully instead of assuming a non-null value.

内容的提问来源于stack exchange,提问作者Tiago

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:44:37