Search code examples
ibatismybatis

Does MyBatis not allow more than 1 argument in SelectProvider?


I have a mapper method like this :

@InsertProvider(class=com.something.class, method="doSomething")
public void insertSomething(Set<Integer> set, int guideId);

and in the something class, I have a method :

public String doSomething(Set<Integer> set, int guideId){
  // do something and returna a query
}

It gives me an error :

Error creating SqlSource for SqlProvider. Method 'doSomething' not found in SqlProvider 'com.something.class'

When I debugged the issue.. I found that in the constructor of ProviderSqlResource, it throws this exception if the no. of arguments are 2 or more. I can't think of any reason why they would do that. What's the workaround ?

Here is the method :

public ProviderSqlSource(Configuration config, Object provider) {
    String providerMethodName = null;
    try {
      this.sqlSourceParser = new SqlSourceBuilder(config);
      this.providerType = (Class<?>) provider.getClass().getMethod("type").invoke(provider);
      providerMethodName = (String) provider.getClass().getMethod("method").invoke(provider);

      for (Method m : this.providerType.getMethods()) {
        if (providerMethodName.equals(m.getName())) {
          if (m.getParameterTypes().length < 2
              && m.getReturnType() == String.class) {
            this.providerMethod = m;
            this.providerTakesParameterObject = m.getParameterTypes().length == 1;
          }
        }
      }
    } catch (Exception e) {
      throw new BuilderException("Error creating SqlSource for SqlProvider.  Cause: " + e, e);
    }
    if (this.providerMethod == null) {
      throw new BuilderException("Error creating SqlSource for SqlProvider. Method '"
          + providerMethodName + "' not found in SqlProvider '" + this.providerType.getName() + "'.");
    }
  }

Solution

  • It turns out that we can pass any number of arguments in methods annotated with SelectProvider (or any other provider). But the method actually providing the query (doSomething, in my case) will actually receive a single argument i.e. a map wrapper around all the arguments. For example, if the arguments were as in the questions above (a set and an integer), we can access them from the map (called parametersMap) as follows :

    Set<Integer> nums = (Set<Integer>) parametersMap.get("0"); 
    int groupId = (Integer) parametersMap.get("1");
    

    The first parameter is keyed with "0" and the second with "1" and so on.

    IMHO, the arguments should have been keyed with their names so that we could do something like :

    parametersMap.get("set");
    parametersMap.get("guideId")
    

    It would probably have been more clean. But that's how its implemented.