This gave me a tough time. The other answer pretty much helps with querying an object by the field value of an hashmap if you know the key for the field. But what if you don't know the key by which the object will be queried? I labored for hours trying to figure out what's wrong even after I followed Noki's very good explanation exactly.
In my case, I have a Customer class that has a hashmap field to store account objects.
public class Customer {
private String firstName;
private String lastName;
private Map<String, Account> customerAccounts = new HashMap<>();
//Constructors, getters, setters...
}
A data Model collection looks something like this
{
firstName: "firstname",
lastName: "lastname",
customerAccounts: {
"0123456789": {
firstName: "firstName",
lastName: "lastname",
accoutNumber: "0123456789",
accountType: "Savings"
},
"1012234494": {
firstName: "firstname",
lastName: "lastname",
accoutNumber: "1012234494",
accountType: "Current"
}
}
}
So, I wanted to query the customer from the database by the accountNumber field of the account object inside customerAccounts. Since the keys for every account in each customerAcoounts object in any Customer is unique and dynamic, and no Customer collection has a similar accountNumber with another Customer collection, you'll need to write your query like this:
@Query(value = "{'customerAccount.?0.accountNumber' : ?0}"
Optional<Customer> findCustomerByCustomerAccount(String accountNumber);
The ?0 in 'customerAccount.?0.accountNumber' will take care of the dynamic value, find an object that its key matches exactly the argument coming in and finally check the accountNumber field for that account object.
@Query
annotation, I need to know is it possible to have query with convention? if yes how? @MarcTarin – Parimutuel