I'm trying to come up with a dynamic query, and based on the research I've done, looks like my best option is the select builder since I want to use annotations rather than XMLs.
I have two parameters; a list and an object that I want to pass to this query builder method. I can use the object without an issue, but can't access to the list from the method.
Here is my mapper interface:
@SelectProvider(type = ProductProvider.class, method = "getProductByBrandByCategory")
List<Product> getProductListByBrandByCategory(@Param("brandList") List<Brand> brandList, @Param("category") Category category);
Here is the getProductByBrandByCategory method that is on ProductProvider class:
public String getProductByBrandByCategory(Map params) {
return new SQL() {{
SELECT("*");
FROM("product");
WHERE("category_id = #{category.id}");
}}.toString();
}
Basically, I'm trying to iterate through the list to add and/or/where statements based on the elements on the list.
Is there a way I can access to brandList element? My guess is that it is part of the Maps param, but don't know how to access it.
Thanks in advance.
See this question for an example how to get to parameters in colection. Code example from cited question
public class CategoryDaoSelectProvider {
public static String findByParentIdAndName(Map<String, Object> params) {
Long parentId = (Long)params.get("parentId"); // WHY IS THIS HERE???
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT COUNT(id) FROM Category ");
if (parentId == null) {
buffer.append("WHERE parentId IS NULL ");
} else {
buffer.append("WHERE parentId = #{parentId} ");
}
buffer.append("AND LOWER(name) = LOWER(#{name}) ");
return buffer.toString();
}
}
Other solutions are
You could use MyBatis Velocity to use the Apache Velocity scripting language to generate your dynamic SQL queries.
You could also use XML-based mapper definitions, they work realy well for your case
Quoting offical documentation, section 'Mapper Annotations'
Java Annotations are unfortunately limited in their expressiveness and flexibility. Despite a lot of time spent in investigation, design and trials, the most powerful MyBatis mappings simply cannot be built with Annotations
From my commercial experience myBatis XML configuration works really well (we use myBatis with Spring). Amount boilerplate code is minimal- just queries and resultMaps . XML syntax is easy to read, even with some logic in XML tags (if,foreach, etc). Annotation based configuration requires complex, nested annotations even for simplest mappings and does not looks good for me. We still have annotations for some mapers but for new code I prefer XML.
IntelliJ IDEA links mapper interface methods with XML SQL definitions, so navigation is easy.