sqlCommand

  • Author: HuiFer
  • Description: 该文介绍 mybatis sqlCommand 类的源码
  • 源码阅读工程: SourceHot-Mybatis

  • org.apache.ibatis.binding.MapperMethod.SqlCommand

  1. /**
  2. * 核心内容: sql id , Sql 类型
  3. */
  4. public static class SqlCommand {
  5. /**
  6. * sql id
  7. */
  8. private final String name;
  9. /**
  10. * sql 类型select|update|delete|insert|...
  11. */
  12. private final SqlCommandType type;
  13. /**
  14. * 根据传递的参数 设置sql的一些属性 , sql id , type .
  15. *
  16. * @param configuration
  17. * @param mapperInterface
  18. * @param method
  19. */
  20. public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
  21. // 方法名
  22. final String methodName = method.getName();
  23. final Class<?> declaringClass = method.getDeclaringClass();
  24. // Statement 实质是sql
  25. MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
  26. configuration);
  27. if (ms == null) {
  28. if (method.getAnnotation(Flush.class) != null) {
  29. name = null;
  30. type = SqlCommandType.FLUSH;
  31. } else {
  32. throw new BindingException("Invalid bound statement (not found): "
  33. + mapperInterface.getName() + "." + methodName);
  34. }
  35. } else {
  36. name = ms.getId();
  37. type = ms.getSqlCommandType();
  38. if (type == SqlCommandType.UNKNOWN) {
  39. throw new BindingException("Unknown execution method for: " + name);
  40. }
  41. }
  42. }
  43. public String getName() {
  44. return name;
  45. }
  46. public SqlCommandType getType() {
  47. return type;
  48. }
  49. /**
  50. * @param mapperInterface mapper.class
  51. * @param methodName 方法名
  52. * @param declaringClass 可能是 mapper.class
  53. * @param configuration
  54. * @return
  55. */
  56. private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
  57. Class<?> declaringClass, Configuration configuration) {
  58. // 接口名称+方法名
  59. String statementId = mapperInterface.getName() + "." + methodName;
  60. if (configuration.hasStatement(statementId)) {
  61. // 从 configuration 获取
  62. return configuration.getMappedStatement(statementId);
  63. } else if (mapperInterface.equals(declaringClass)) {
  64. return null;
  65. }
  66. // new 一个新的实例
  67. for (Class<?> superInterface : mapperInterface.getInterfaces()) {
  68. if (declaringClass.isAssignableFrom(superInterface)) {
  69. MappedStatement ms = resolveMappedStatement(superInterface, methodName,
  70. declaringClass, configuration);
  71. if (ms != null) {
  72. return ms;
  73. }
  74. }
  75. }
  76. return null;
  77. }
  78. }

image-20191218191512184

image-20191218191550550