javacommercetoolssphere.io

How can I find a ProductVariant by his variantKey?


In my project I am now needing to obtain the variant of the product from the variantKey, but I have not found any method in the JVM SDK to do it. I tried to do it using the ProductByKeyGet method, but I only get the product if the value corresponds to the root key of the product, but if the value corresponds to the variantKey it does not return anything to me.

Does anyone know any way to get the variant from its VariantKey?

Thanks in advance. Miguel de la Hoz


Solution

  • Today we released version 1.29.0 of our JVM SDK - where we added the missing support for querying product variants by key (see https://github.com/commercetools/commercetools-jvm-sdk/issues/1679). With this version you can then write the query in a typesafe fashion:

    String myKey = "foo";
    ProductProjectionType projectionType = ProductProjectionType.CURRENT;
    
    ProductProjectionQuery query =
        ProductProjectionQuery.of(projectionType)
             .withPredicates(product -> product.allVariants()
                .where(variant -> variant.key().is(myKey)));
    

    Hope this helps!