I am writing rest apis which supports filtering with spring data jpa and mysql as a database. I can do this by using ExampleMatcher and Example. But there is one case where there can be multiple values can be passed for one field(means i need to use in clause here). And this can't be done using exampleMatcher. I am putting example here to explain my use case. Here is my class.
public class Merchant {
private String merchantId;
private String merchantGroupId;
private String status;
}
Here is my JPA repository implementation.
public interface MerchantRepository extends JpaRepository<Merchant, Serializable> {
public List<Merchant> findByMerchantGroupIdIn(List<String> merchantGroupIds);
public List<Merchant> findByMerchantGroupIdInAndStatus(List<String> merchantGroupIds, String status);
public List<Merchant> findByMerchantId(String merchantId);
public List<Merchant> findByMerchantIdAndStatus(String merchantId, String status);
public List<Merchant> findByStatus(String status);
}
And this is how I am calling this:
if (merchantGroupIds != null && merchantId == null && status == null) {
List<Merchant> merchants = findByMerchantGroupIdIn(merchantGroupIds);
} else if (merchantGroupIds != null && status != null && merchantId == null) {
List<Merchant> merchants = findByMerchantGroupIdInAndStatus(merchantGroupIds, status);
} else if (merchantGroupIds == null && merchantId != null && status == null) {
List<Merchant> merchants = findByMerchantId(merchantId);
} and many if else
I want to avoid these all if else and one generic function which will take care of all null values and will ignore nulls. Is there is any way to achieve this using spring data?