How does the mybatis parameter replacement work in @SelectProvider

人盡茶涼 提交于 2019-12-05 11:49:05

SelectProviders receive parameters in 2 ways: as items in the params Map argument and as #{parentId} (in your example). You code shows parentId being checked before it is used in the select statement. The parentId variable is needed because you can't query #{parentId}.

Btw, this isn't the best implementation of a SelectProviders, you're supposed to use SELECT(), WHERE() and SQL() at the end to return the compiled statement. I guess your example works too.

You could rewrite that piece of code as follows, which is perhaps a bit clearer? The actual value of parentId is indeed not necessary, but the info on whether or not the parameter is present is required.

 // ...
 boolean hasIdParam = params.containsKey("parentId");

 StringBuffer buffer = new StringBuffer();
 buffer.append("SELECT COUNT(id) FROM Category ");

 if (!hasIdParam) {
    buffer.append("WHERE parentId IS NULL ");
 } else {
    buffer.append("WHERE parentId = #{parentId} ");
 }
 // ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!