Home > Back-end >  Return a Mapped result in JPA Spring Boot
Return a Mapped result in JPA Spring Boot

Time:08-24

So I have a database with a products table, the requirement is somehow that I pass the list of product codes and it returns me the mapped productName with the corresponding productCode.

Something like this: Map<String,String> getProductNamesByCodes(List ProductCodes);

I am new to Java & SpringBoot, I need the repository code in any query or customized function, is this possible?

  • We use JPA.
  • Products table has other fields too.

The BruteForce way is to run the for loop in the list of productCodes and fill the map by finding name one by one.

CodePudding user response:

You could make a Spring Data JPA repository query like this:

Stream<Product> findAllByProductCode(Collection<String> productCodes);

Which will give you a Java Stream. You should then be able to map the elements of the Stream to a Map like the one you're describing.

Map<String, String> productMap = repository
  .findAllByProductCodes(productCodes)
  .collect(toMap(Product::getProductCode, Product::getProductName));

EDIT: I should point out that this will fetch all the data fields that are specified in the Product JPA entity, not only the productCode and productName. This may be worth being aware of if Product defines an eagerly loaded collection, for example.

  • Related