Skip to content
Advertisement

Mapstruct: Returning null when trying to map a field inside an embedded object

We were given an assignment to recreate a simple version of the Twitter API in Spring using Mapstruct.

We are returning a List<UserDto> that should return the field username from the embedded object Credentials.

We mapped this as follows:

JavaScript

Our UserDto is specified like this:

JavaScript

Our User entity has an embedded object named credentials, where the username and password of the user are stored in String format (I know this is dumb, this is just an assignment).

JavaScript

Long story short, when we GET all users, we should receive this (these are fake names and numbers):

JavaScript

But instead, we receive a null value for username:

JavaScript

I know the value username in credentials exists, as it exists in the table it is stored:

enter image description here

And it is accessible because other methods that call user.getCredentials().getUsername() return the right username.

I have tried pretty much everything. I have run mvn clean install, renamed variables. I’m out of ideas. Any help would be appreciated.

Advertisement

Answer

The way you’re trying to use @Mapping on a collection-mapping method isn’t supported at the moment. You need to declare an explicit mapping from User to UserDto, and apply the annotation on it instead:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement