简体   繁体   中英

Return a Mapped result in JPA Spring Boot

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM