Dto转Entity后调用getId出现NPE问题求助(MapStruct/ModelMapper)
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
idfield. - For MapStruct: Ensure your mapper interface doesn’t attempt to map a non-existent
idfrom 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

