Many to One Assistance

213 views
Skip to first unread message

Stefan du Preez

unread,
Mar 8, 2018, 7:31:44 AM3/8/18
to mapstruct-users
Hi,

I am quite new to Spring and Mapstruct, I am not sure if this is the correct place to ask this, but I have the following use case I really need assistance with:

































It is the typical Many-To-One use case, with added fields. 

Json_object and json_attribute are both mapped by using MapStruct. 
I am using @EmbeddedId on the JsonMapping entity.
If I write the JsonMappingMapper manually I can get it to work, but nowhere can I find anything about mapping Composite Keys in MapStruct.

 I need to figure out how to get MapStruct to generate the following to be able to save changes on the json_mapping table:

public JsonMapping dtoToEntity(JsonObject jsonObject, JsonMappingDto dto) {
 
JsonMappingId id = new JsonMappingId(jsonObject.getJsonObjectId(), dto.getJsonAttribute().getJsonAttrId());
 
JsonMapping entity = jsonMappingRepository.findOne(id);
 
if (entity == null) {
   entity
= new JsonMapping();
 
}
 entity
.setId(new JsonMappingId(jsonObject.getJsonObjectId(), dto.getJsonAttribute().getJsonAttrId()));
 entity
.setJsonAttribute(jsonAttributeMapper.dtoToEntity(dto.getJsonAttribute()));
 entity
.setJsonObject(jsonObject);
 
return entity;
 
}

Any help would be greatly appreciated :)

Regards
Stefan du Preez

Sjaak Derksen

unread,
Mar 17, 2018, 6:26:36 AM3/17/18
to mapstruct-users
For my understanding:
Is this a one-time-problem -> don't bother. Use the manual mapping method above.
Is this a recurring-problem -> you might want to look into @BeforeMapping. This way you can delegate fetching the entity (http://mapstruct.org/documentation/stable/reference/html/#customizing-mappings-with-before-and-after) and setting the id to a specific method. If you have control over the `JsonMapping`  and the `JsonObject` you can probably generalise this into an interface.

Sjaak Derksen

unread,
Mar 17, 2018, 9:35:16 AM3/17/18
to mapstruct-users


On Saturday, March 17, 2018 at 11:26:36 AM UTC+1, Sjaak Derksen wrote:
For my understanding:
Is this a one-time-problem -> don't bother. Use the manual mapping method above.
Is this a recurring-problem -> you might want to look into @BeforeMapping. This way you can delegate fetching the entity (http://mapstruct.org/documentation/stable/reference/html/#customizing-mappings-with-before-and-after) and setting the id to a specific method. If you have control over the `JsonMapping`  and the `JsonObject` you can probably generalise this into an interface.

@ObjectFactory is a better option.. I added an example: https://github.com/mapstruct/mapstruct-examples/pull/39

Sjaak Derksen

unread,
Mar 17, 2018, 4:36:28 PM3/17/18
to mapstruct-users
Reply all
Reply to author
Forward
0 new messages