How to use PreparedStatement efficiently?

前提是你 提交于 2019-12-08 13:50:38

The advantage for declaritively defined queries via @NamedQuery is that they will be precompiled, can be cached within the secondary cache and syntactically validated on startup if you enable it within the persistence.xml using the JPA non-hibernate specific API.

So if you plan on executing a query, using only JPA, often it is probably best to use NamedQuery and cache the query.

So for JPA using hibernate you could do something like this:

            @NamedQuery(name="AbstractBaseQuestion.findAllInstancesByGroupID", query="SELECT q FROM AbstractBaseQuestion q WHERE q.isTemplate = FALSE", hints={@QueryHint(name="org.hibernate.cacheable", value="true"),@QueryHint(name="org.hibernate.cacheMode", value="NORMAL"),}),

Within your persistence.xml for hibernate you can validate these @NamedQueries on startup:

      <property name="hibernate.hbm2ddl.auto" value="validate"/>

Now the first method you suggested can be cached and precompiled if you use the Hibernate Session API. I imagine there are equivalents on EclipseLink and other ORM's but at this point you are using non-JPA features which could make moving from one JPA implementation to another difficult.

If you don't do that extra implementation specific work your query is going to not be cached and you will pay a performance penalty.

I hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!