SelectProvider中工作

SelectProvider中工作

本文介绍了mybatis参数替换如何在@SelectProvider中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一些我想要理解的代码,我在 @SelectProvider 上找到的任何搜索都发现了很多东西。

I've in inherited some code that I'm trying to understand and any searching I do to find something on @SelectProvider turns up a whole lot of nothing.

Java DAO

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

选择提供商

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

param parentId在此代码中的用途是什么?据我所知,除非神奇地将#{parentId}替换为值,否则它实际上什么都不做。在这种情况下,这个参数是不是用过的? mybatis 在哪里实际注入查询?

What purpose does the param parentId serve in this code? As far as I can tell it never actually does anything unless somehow magically the #{parentId} is replaced with the value. Is this param just not used in this situation? Where does mybatis actually do the injections into the query?

推荐答案

SelectProviders以两种方式接收参数:作为params Map参数中的项目和#{parentId}(在您的示例中)。您的代码显示parentId在select语句中使用之前被检查。需要parentId变量,因为你无法查询#{parentId}。

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}.

顺便说一句,这不是SelectProviders的最佳实现,你应该使用SELECT(),WHERE()和SQL()在最后返回编译语句。我猜你的例子也有效。

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.

这篇关于mybatis参数替换如何在@SelectProvider中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:20