Skip to content
Snippets Groups Projects

feat: Move BaseEntityMapper to persistence package to eliminate duplication across projects

1 file
+ 62
0
Compare changes
  • Side-by-side
  • Inline
 
/*********************************************************************
 
* Copyright (c) 2022, 2024 Eclipse Foundation.
 
*
 
* This program and the accompanying materials are made
 
* available under the terms of the Eclipse Public License 2.0
 
* which is available at https://www.eclipse.org/legal/epl-2.0/
 
*
 
* Author: Martin Lowe <martin.lowe@eclipse-foundation.org>
 
*
 
* SPDX-License-Identifier: EPL-2.0
 
**********************************************************************/
 
package org.eclipsefoundation.persistence.mapper;
 
 
import org.eclipsefoundation.persistence.dao.PersistenceDao;
 
import org.eclipsefoundation.persistence.dto.BareNode;
 
import org.mapstruct.Context;
 
import org.mapstruct.InheritInverseConfiguration;
 
import org.mapstruct.ObjectFactory;
 
import org.mapstruct.TargetType;
 
 
/**
 
* Indicates an entity mapping between DTOs and models. Is used to help simplify
 
* the lookups where possible.
 
*
 
* @author Martin Lowe
 
*
 
* @param <T> the DTO object in the mapping pair
 
* @param <U> the model object in the mapping pair
 
*/
 
public interface BaseEntityMapper<T extends BareNode, U> {
 
 
U toModel(T dtoEntity);
 
 
@InheritInverseConfiguration
 
T toDTO(U model, @Context PersistenceDao repo);
 
 
/**
 
* Used for generic BareNode lookups. This assumes that the string in the
 
* inverse is the key of the field. This will
 
* be used in a lookup of a reference of the object to be used in the DTO mapped
 
* object.
 
*
 
* @param <E> the BareNode actual type
 
* @param id the string ID of the object to lookup
 
* @param repo the passed repo context to be used for reference lookups
 
* @param targetType the injected class type reference
 
* @return a reference to the target entity if it exists, or a new object to be
 
* persisted.
 
*/
 
@ObjectFactory
 
default <E extends BareNode> E lookup(String id, @Context PersistenceDao repo, @TargetType Class<E> targetType) {
 
E entity = repo.getReference(id, targetType);
 
if (entity == null) {
 
try {
 
entity = targetType.getConstructor().newInstance();
 
} catch (Exception e) {
 
throw new IllegalStateException("Could not access no-param constructor of entity type", e);
 
}
 
}
 
return entity;
 
}
 
}
Loading