专栏首页码匠的流水账聊聊spring data jpa的JpaQueryLookupStrategy

聊聊spring data jpa的JpaQueryLookupStrategy

本文主要研究一下spring data jpa的JpaQueryLookupStrategy

QueryLookupStrategy

spring-data-commons-2.1.6.RELEASE-sources.jar!/org/springframework/data/repository/query/QueryLookupStrategy.java

public interface QueryLookupStrategy {

    public static enum Key {

        CREATE, USE_DECLARED_QUERY, CREATE_IF_NOT_FOUND;

        /**
         * Returns a strategy key from the given XML value.
         *
         * @param xml
         * @return a strategy key from the given XML value
         */
        @Nullable
        public static Key create(String xml) {

            if (!StringUtils.hasText(xml)) {
                return null;
            }

            return valueOf(xml.toUpperCase(Locale.US).replace("-", "_"));
        }
    }

    /**
     * Resolves a {@link RepositoryQuery} from the given {@link QueryMethod} that can be executed afterwards.
     *
     * @param method will never be {@literal null}.
     * @param metadata will never be {@literal null}.
     * @param factory will never be {@literal null}.
     * @param namedQueries will never be {@literal null}.
     * @return
     */
    RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
            NamedQueries namedQueries);
}
  • QueryLookupStrategy定义了Key枚举,有CREATE, USE_DECLARED_QUERY, CREATE_IF_NOT_FOUND这些类型
  • QueryLookupStrategy有一个抽象类为AbstractQueryLookupStrategy,它有三个实现子类,分别是CreateQueryLookupStrategy、DeclaredQueryLookupStrategy、CreateIfNotFoundQueryLookupStrategy
  • QueryLookupStrategy还定义了resolveQuery方法用于将QueryMethod解析为RepositoryQuery

RepositoryQuery

spring-data-commons-2.1.6.RELEASE-sources.jar!/org/springframework/data/repository/query/RepositoryQuery.java

public interface RepositoryQuery {

    /**
     * Executes the {@link RepositoryQuery} with the given parameters.
     *
     * @param parameters must not be {@literal null}.
     * @return execution result. Can be {@literal null}.
     */
    @Nullable
    Object execute(Object[] parameters);

    /**
     * Returns the related {@link QueryMethod}.
     *
     * @return never {@literal null}.
     */
    QueryMethod getQueryMethod();
}
  • RepositoryQuery接口定义了两个方法分别是execute、getQueryMethod;它有2个抽象类,一个是AbstractJpaQuery、另外一个是继承AbstractJpaQuery的AbstractStringBasedJpaQuery;AbstractJpaQuery有3个实现子类,分别是NamedQuery、PartTreeJpaQuery、StoredProcedureJpaQuery;AbstractStringBasedJpaQuery有两个实现子类,分别是SimpleJpaQuery及NativeJpaQuery

AbstractQueryLookupStrategy

spring-data-jpa-2.1.6.RELEASE-sources.jar!/org/springframework/data/jpa/repository/query/JpaQueryLookupStrategy.java

    /**
     * Base class for {@link QueryLookupStrategy} implementations that need access to an {@link EntityManager}.
     *
     * @author Oliver Gierke
     * @author Thomas Darimont
     */
    private abstract static class AbstractQueryLookupStrategy implements QueryLookupStrategy {

        private final EntityManager em;
        private final QueryExtractor provider;

        /**
         * Creates a new {@link AbstractQueryLookupStrategy}.
         *
         * @param em
         * @param extractor
         */
        public AbstractQueryLookupStrategy(EntityManager em, QueryExtractor extractor) {

            this.em = em;
            this.provider = extractor;
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.data.repository.query.QueryLookupStrategy#resolveQuery(java.lang.reflect.Method, org.springframework.data.repository.core.RepositoryMetadata, org.springframework.data.projection.ProjectionFactory, org.springframework.data.repository.core.NamedQueries)
         */
        @Override
        public final RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
                NamedQueries namedQueries) {
            return resolveQuery(new JpaQueryMethod(method, metadata, factory, provider), em, namedQueries);
        }

        protected abstract RepositoryQuery resolveQuery(JpaQueryMethod method, EntityManager em, NamedQueries namedQueries);
    }
  • AbstractQueryLookupStrategy实现了QueryLookupStrategy接口定义的resolveQuery方法,不过它调用了自己定义的抽象方法resolveQuery

CreateQueryLookupStrategy

spring-data-jpa-2.1.6.RELEASE-sources.jar!/org/springframework/data/jpa/repository/query/JpaQueryLookupStrategy.java

    /**
     * {@link QueryLookupStrategy} to create a query from the method name.
     *
     * @author Oliver Gierke
     * @author Thomas Darimont
     */
    private static class CreateQueryLookupStrategy extends AbstractQueryLookupStrategy {

        private final PersistenceProvider persistenceProvider;
        private final EscapeCharacter escape;

        public CreateQueryLookupStrategy(EntityManager em, QueryExtractor extractor, EscapeCharacter escape) {

            super(em, extractor);

            this.persistenceProvider = PersistenceProvider.fromEntityManager(em);
            this.escape = escape;
        }

        @Override
        protected RepositoryQuery resolveQuery(JpaQueryMethod method, EntityManager em, NamedQueries namedQueries) {
            return new PartTreeJpaQuery(method, em, persistenceProvider, escape);
        }
    }
  • CreateQueryLookupStrategy继承了AbstractQueryLookupStrategy,其resolveQuery方法创建的是PartTreeJpaQuery

DeclaredQueryLookupStrategy

spring-data-jpa-2.1.6.RELEASE-sources.jar!/org/springframework/data/jpa/repository/query/JpaQueryLookupStrategy.java

    /**
     * {@link QueryLookupStrategy} that tries to detect a declared query declared via {@link Query} annotation followed by
     * a JPA named query lookup.
     *
     * @author Oliver Gierke
     * @author Thomas Darimont
     */
    private static class DeclaredQueryLookupStrategy extends AbstractQueryLookupStrategy {

        private final QueryMethodEvaluationContextProvider evaluationContextProvider;

        /**
         * Creates a new {@link DeclaredQueryLookupStrategy}.
         *
         * @param em
         * @param extractor
         * @param evaluationContextProvider
         */
        public DeclaredQueryLookupStrategy(EntityManager em, QueryExtractor extractor,
                QueryMethodEvaluationContextProvider evaluationContextProvider) {

            super(em, extractor);
            this.evaluationContextProvider = evaluationContextProvider;
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy.AbstractQueryLookupStrategy#resolveQuery(org.springframework.data.jpa.repository.query.JpaQueryMethod, javax.persistence.EntityManager, org.springframework.data.repository.core.NamedQueries)
         */
        @Override
        protected RepositoryQuery resolveQuery(JpaQueryMethod method, EntityManager em, NamedQueries namedQueries) {

            RepositoryQuery query = JpaQueryFactory.INSTANCE.fromQueryAnnotation(method, em, evaluationContextProvider);

            if (null != query) {
                return query;
            }

            query = JpaQueryFactory.INSTANCE.fromProcedureAnnotation(method, em);

            if (null != query) {
                return query;
            }

            String name = method.getNamedQueryName();
            if (namedQueries.hasQuery(name)) {
                return JpaQueryFactory.INSTANCE.fromMethodWithQueryString(method, em, namedQueries.getQuery(name),
                        evaluationContextProvider);
            }

            query = NamedQuery.lookupFrom(method, em);

            if (null != query) {
                return query;
            }

            throw new IllegalStateException(
                    String.format("Did neither find a NamedQuery nor an annotated query for method %s!", method));
        }
    }
  • DeclaredQueryLookupStrategy继承了AbstractQueryLookupStrategy,其resolveQuery方法借助JpaQueryFactory.INSTANCE.fromQueryAnnotation、JpaQueryFactory.INSTANCE.fromProcedureAnnotation、NamedQuery.lookupFrom来生成

CreateIfNotFoundQueryLookupStrategy

spring-data-jpa-2.1.6.RELEASE-sources.jar!/org/springframework/data/jpa/repository/query/JpaQueryLookupStrategy.java

    /**
     * {@link QueryLookupStrategy} to try to detect a declared query first (
     * {@link org.springframework.data.jpa.repository.Query}, JPA named query). In case none is found we fall back on
     * query creation.
     *
     * @author Oliver Gierke
     * @author Thomas Darimont
     */
    private static class CreateIfNotFoundQueryLookupStrategy extends AbstractQueryLookupStrategy {

        private final DeclaredQueryLookupStrategy lookupStrategy;
        private final CreateQueryLookupStrategy createStrategy;

        /**
         * Creates a new {@link CreateIfNotFoundQueryLookupStrategy}.
         *
         * @param em
         * @param extractor
         * @param createStrategy
         * @param lookupStrategy
         */
        public CreateIfNotFoundQueryLookupStrategy(EntityManager em, QueryExtractor extractor,
                CreateQueryLookupStrategy createStrategy, DeclaredQueryLookupStrategy lookupStrategy) {

            super(em, extractor);

            this.createStrategy = createStrategy;
            this.lookupStrategy = lookupStrategy;
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy.AbstractQueryLookupStrategy#resolveQuery(org.springframework.data.jpa.repository.query.JpaQueryMethod, javax.persistence.EntityManager, org.springframework.data.repository.core.NamedQueries)
         */
        @Override
        protected RepositoryQuery resolveQuery(JpaQueryMethod method, EntityManager em, NamedQueries namedQueries) {

            try {
                return lookupStrategy.resolveQuery(method, em, namedQueries);
            } catch (IllegalStateException e) {
                return createStrategy.resolveQuery(method, em, namedQueries);
            }
        }
    }
  • CreateIfNotFoundQueryLookupStrategy继承了AbstractQueryLookupStrategy,它的构造器要求传入DeclaredQueryLookupStrategy、CreateQueryLookupStrategy参数,其resolveQuery方法先是借助DeclaredQueryLookupStrategy来创建RepositoryQuery,如果抛出的是IllegalStateException,再借助CreateQueryLookupStrategy来创建RepositoryQuery

JpaQueryLookupStrategy

spring-data-jpa-2.1.6.RELEASE-sources.jar!/org/springframework/data/jpa/repository/query/JpaQueryLookupStrategy.java

public final class JpaQueryLookupStrategy {

    /**
     * Private constructor to prevent instantiation.
     */
    private JpaQueryLookupStrategy() {}

    //......

    /**
     * Creates a {@link QueryLookupStrategy} for the given {@link EntityManager} and {@link Key}.
     *
     * @param em must not be {@literal null}.
     * @param key may be {@literal null}.
     * @param extractor must not be {@literal null}.
     * @param evaluationContextProvider must not be {@literal null}.
     * @param escape
     * @return
     */
    public static QueryLookupStrategy create(EntityManager em, @Nullable Key key, QueryExtractor extractor,
            QueryMethodEvaluationContextProvider evaluationContextProvider, EscapeCharacter escape) {

        Assert.notNull(em, "EntityManager must not be null!");
        Assert.notNull(extractor, "QueryExtractor must not be null!");
        Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");

        switch (key != null ? key : Key.CREATE_IF_NOT_FOUND) {
            case CREATE:
                return new CreateQueryLookupStrategy(em, extractor, escape);
            case USE_DECLARED_QUERY:
                return new DeclaredQueryLookupStrategy(em, extractor, evaluationContextProvider);
            case CREATE_IF_NOT_FOUND:
                return new CreateIfNotFoundQueryLookupStrategy(em, extractor,
                        new CreateQueryLookupStrategy(em, extractor, escape),
                        new DeclaredQueryLookupStrategy(em, extractor, evaluationContextProvider));
            default:
                throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key));
        }
    }
}
  • JpaQueryLookupStrategy提供一个静态方法create用于根据不同的QueryLookupStrategy.Key来创建不同的QueryLookupStrategy,默认是Key.CREATE_IF_NOT_FOUND,即创建CreateIfNotFoundQueryLookupStrategy

小结

  • QueryLookupStrategy定义了Key枚举,有CREATE, USE_DECLARED_QUERY, CREATE_IF_NOT_FOUND这些类型;QueryLookupStrategy有一个抽象类为AbstractQueryLookupStrategy,它有三个实现子类,分别是CreateQueryLookupStrategy、DeclaredQueryLookupStrategy、CreateIfNotFoundQueryLookupStrategy;QueryLookupStrategy还定义了resolveQuery方法用于将QueryMethod解析为RepositoryQuery
  • AbstractQueryLookupStrategy实现了QueryLookupStrategy接口定义的resolveQuery方法,不过它调用了自己定义的抽象方法resolveQuery
    • CreateQueryLookupStrategy继承了AbstractQueryLookupStrategy,其resolveQuery方法创建的是PartTreeJpaQuery(解析方法名);
    • DeclaredQueryLookupStrategy继承了AbstractQueryLookupStrategy,其resolveQuery方法借助JpaQueryFactory.INSTANCE.fromQueryAnnotation(解析@Query注解)、JpaQueryFactory.INSTANCE.fromProcedureAnnotation(解析@Procedure注解)、NamedQuery.lookupFrom(解析@NamedQuery注解)来生成;
    • CreateIfNotFoundQueryLookupStrategy继承了AbstractQueryLookupStrategy,它的构造器要求传入DeclaredQueryLookupStrategy、CreateQueryLookupStrategy参数,其resolveQuery方法先是借助DeclaredQueryLookupStrategy来创建RepositoryQuery,如果抛出的是IllegalStateException,再借助CreateQueryLookupStrategy来创建RepositoryQuery
  • JpaQueryLookupStrategy提供一个静态方法create用于根据不同的QueryLookupStrategy.Key来创建不同的QueryLookupStrategy,默认是Key.CREATE_IF_NOT_FOUND,即创建CreateIfNotFoundQueryLookupStrategy

doc

  • JpaQueryLookupStrategy

本文分享自微信公众号 - 码匠的流水账(geek_luandun)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-04-15

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • java jdk 8反编译工具JD-GUI、procyon-decompiler、luyten、crf下载使用简介

    如果版本>=1.8 ,可以使用 procyon-decompiler,不过是命令行界面

    noteless
  • Vue 3.0对Web开发的影响

    去年11月,Vue创建者Evan You展示了Vue 3.0的关键更新 - 这是不断上升的Javascript框架的最新版本。 这些优化使Vue更高效,模块化且...

    grain先森
  • Android:这是一份全面 & 详细的Android代码命名规范

    Carson.Ho
  • 龙岗一个月350的出租房,我搬出来了

    好久没写文章了,因为最近的实在是太忙了,看到这一期的征文,不禁让我回想起了当初刚毕业的那个自己,一时之间感慨万千。

    孤独键客
  • 聊聊jvm的-XX:MaxDirectMemorySize

    codecraft
  • 创建型模式:单例模式

    Ensure a class has only one instance, and provide a global point of access to it...

    LieBrother
  • 聊聊openjdk的BufferPoolMXBean

    java.management/java/lang/management/PlatformManagedObject.java

    codecraft
  • Kotlin | 2.Kotlin基础

    在定义了val变量的代码块执行期间,val变量只能进行唯一一次初始化。但是,如果编译器能确保只有唯一一条初始化语句被执行,可以根据条件使用不同的值来初始化它:

    Jingbin
  • Java12的新特性

    对于需要返回值的switch expression要么正常返回值要么抛出异常,以下这两种写法都是错误的

    codecraft
  • 部分算法总结

    希尔排序(Shell's Sort)是插入排序的一种又称“缩小增量排序”(Diminishing Increment Sort),是直接插入排序算法的一种更高效...

    Dream城堡

扫码关注云+社区

领取腾讯云代金券