How parameter replacement mybatis works in @SelectProvider

I have inherited some code that I am trying to understand, and any search I do to find something on @SelectProvider has nothing to do.

Java DAO

 @SelectProvider(type = CategoryDaoSelectProvider.class, method = "findByParentIdAndName") Category findByParentIdAndName(@Param("parentId") Long parentId, @Param("name") String name); 

Choose a supplier

 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(); } } 

What is the purpose of the parentId parameter in this code? As far as I can tell, it never does anything if in some magic way # {parentId} is replaced with a value. Is this parameter simply not used in this situation? Where mybatis actually inject the request?

+4
source share
1 answer

SelectProviders receive parameters in two ways: as elements in the Params Map argument and as # {parentId} (in your example). You indicate that parentId is checked before it is used in the select statement. The parentId variable is necessary because you cannot request # {parentId}.

Btw, this is not the best implementation of SelectProviders, you must use SELECT (), WHERE (), and SQL () at the end to return a compiled statement. I think your example also works.

+5
source

Source: https://habr.com/ru/post/1391659/


All Articles