Reputation: 2298
I have a domain object Item
:
Item fields: a
, b
, c
It has a lot more fields in reality.
I know I can create methods like:
findByAAndB(...)
Use @Query(SELECT ... WHERE ...)
on my custom find method
But I still wonder if there is a better solution: What is the easiest to query the items
table given that I may have a bunch of fields to query for at the same time?
If I have a method as shown below, is there a way that automatically maps the fields that are say != null
into a SELECT
?
findBy(Item prototype)
Upvotes: 1
Views: 657
Reputation: 929
public class Item{
String a,b,c;
}
Item item=new Item();
item.setA("a");
Example<Item> itemExample=ExampleOf(item);
List<Item> res=itemRepository.findAll(example);
Source: Query By Example
Upvotes: 1
Reputation: 3522
you can create custom query with entity manager and create dynamic query. for this you have to define all variable with default -1
, which you have to use in query, then get the all variable ache check then value is change or not if change the add variable into query and execute it.
ex.
StringBuilder tempQuery = new StringBuilder("select " + select + " FROM
Area area ");
// cityId
if (cityId != -1) {
tempQuery.append(" and ");
tempQuery.append(" area.FCity.cityId = :cityId ");
}
// rId
if (rId != -1) {
tempQuery.append(" and ");
tempQuery.append(" area.FRestaurantCenter.FRestaurant = :rId ");
}
return tempQuery.toString();
Upvotes: 0