samedi 26 décembre 2020

Are there any alternative ways to reuse RepresentationModelAssemblerSupport

With each Model class i have to create a RepresentationModelAssemblerSupport class, which is kind of redundant, so i write a generic RepresentationModelAssemblerSupport class.

Generic RepresentationModelAssemblerSupport class:

public class ModelAssembler<T, E extends RepresentationModel<E>> extends RepresentationModelAssemblerSupport<T, E> {
    private final Class<E> model;
    public ModelAssembler(Class<?> controllerClass, Class<E> resourceType) {
        super(controllerClass, resourceType);
        model = resourceType;
    }
    @Override
    protected E instantiateModel(T entity) {
        try {
            Constructor<E> constructor = model.getConstructor(entity.getClass());
            return constructor.newInstance(entity);
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
            throw new RuntimeException("lỗi server");
        }
    }

    @Override
    public E toModel(T entity) {
        Class<?> clazz = entity.getClass();
        try {
            Method method = clazz.getMethod("getId");
            Object id = method.invoke(entity);
            return createModelWithId(id, entity);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("lỗi server");
        }
    }
}

It works but i have to use java reflection, which could lead to performance issues since toModel gets called every Request.

Are there any alternative ways to generalise RepresentationModelAssemblerSupport?

Here's an example of Model class:

@Relation(collectionRelation = "products", itemRelation = "product")
@Getter
public class ProductModel extends RepresentationModel<ProductModel> {
    private final UUID id;
    private final String name;
    private final Integer price;
    private final String description;
    public ProductModel(Product product) {
        this.id = product.getId();
        this.name = product.getName();
        this.price = product.getPrice();
        this.description = product.getDescription();
        add(linkTo(methodOn(ProductController.class).getProductColors(product.getId())).withRel("productColors"));
        add(linkTo(methodOn(ProductController.class).getProductTags(product.getId())).withRel("productTags"));
        add(linkTo(methodOn(ThumbnailController.class).getThumbnail(product.getThumbnail().getId())).withRel("thumbnail"));
        add(linkTo(methodOn(ProductController.class).all(0, new PagedResourcesAssembler<>(null, null))).withRel("all"));
    }
}




Aucun commentaire:

Enregistrer un commentaire