Reputation: 100
I am trying to make generic architecture with Java framework Spring Boot.
The mappers I tried doesn't seem to have a generic method like Automapper in .Net Core framework has -> Mapper.Map<TEntity>(source)
.
Is there a way to achieve in Spring Boot generic mapping without passing a target? Because my target is
TEntity
and it couldn't be directly instantiated (T target = new T();
) to pass it directly in method (mapper.map(source, target)
).
There is an example what I want to achieve in C# in .Net Core framework in Service layer.
public virtual TDataTransferObject Insert(TInsertDTO request){
var entity = Mapper.Map<TEntity>(request);
return Mapper.Map<TDataTransferObject>(Repository.Add(entity));
}
Upvotes: 0
Views: 5217
Reputation: 1648
My experience is mostly with ModelMapper and it maps only between two objects or from an object to a target class.
On a quick glance over other popular mappers, they offer similar functionality in that regard, probably because of the Type erasure in Java.
To work around that limitation, type of the generic class should be added as a field to the base class. One solution is to pass it as argument to the base class' constructor. Another is to use reflection:
public abstract class BaseService<E> {
private final Class<E> entityClass;
private final ModelMapper mapper;
protected BaseService(ModelMapper mapper) {
this.mapper = mapper;
entityClass = getEntityClass();
}
@SuppressWarnings("unchecked")
private Class<E> getEntityClass() {
return (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
public <I, O> O insert(I inputData, Class<O> outClass) {
E entity = mapper.map(inputData, entityClass);
O outData = mapper.map(entity, outClass);
return outData;
}
}
public class FooService extends BaseService<Foo> {
public FooService(ModelMapper mapper) {
super(mapper);
}
}
public class Demo {
public static void main(String[] args) {
FooService service = new FooService(new ModelMapper());
Foo foo = new Foo("foo");
Baz baz = service.insert(foo, Baz.class);
}
}
An article comparing Performance of Java Mapping Frameworks
Upvotes: 1