EJB--Query Best Practices
上一篇 / 下一篇 2008-05-10 19:16:01 / 个人分类:EJB
Named Queries
;l:bI8XFPOJG*pZ0First and foremost, we recommend named queries whenever possible. Persistence providersITPUB个人空间@aT%HP
will often take steps to precompile JPQL named queries to SQL as part of the deployment or initializationITPUB个人空间B2i"]'K$mL bg#w$L
phase of an application. This avoids the overhead of continuously parsing JPQL and
-E:f8G*X,~5V B0generating SQL. Even with a cache for converted queries, dynamic query definition will alwaysITPUB个人空间2R Ub3vG*GQ
be less efficient than using named queries.ITPUB个人空间!ZT].](vBC8D'i
Named queries also enforce the best practice of using query parameters. Query parameters
?
s^!\*it0help to keep the number of distinct SQL strings parsed by the database to a minimum.ITPUB个人空间vuyb'{@6H,r` Q
Since databases typically keep a cache of SQL statements on hand for frequently accessed queries,ITPUB个人空间G/vD:l
M:j
this is an essential part of ensuring peak database performance.ITPUB个人空间 ~u-d s*N:c
As we discussed in the Dynamic Query Definition section, query parameters also help toITPUB个人空间H(?%A@v%i'V
avoid security issues caused by concatenating values into query strings. For applications
}Ow*h8V2YJ-|ec
r0exposed to the web, security has to be a concern at every level of an application. You can eitherITPUB个人空间-u Gx_"K0P?1V
spend a lot of effort trying to validate input parameters, or you can use query parameters and
_cWBo/{0let the database do the work for you.ITPUB个人空间P!z/uTt4NNT
When naming queries, decide on a naming strategy early in the application developmentITPUB个人空间+m*L"[:BG
u6@Vz
cycle with the understanding that the query namespace is global for each persistence unit. CollisionsITPUB个人空间
pRX;p)tRnTU
between query names are likely to be a common frustration if there is no establishedITPUB个人空间@'EQ
a-~3z
naming pattern.
XR1p V3q0Finally, using named queries allows for JPQL queries to be overridden with SQL queries orITPUB个人空间0C$Y(l@,bO5N
even with vendor-specific languages and expression frameworks. For applications migratingITPUB个人空间I%k"v,A
a
from an existing object-relational mapping solution, it is quite likely that the vendor will provideITPUB个人空间qV#Rt4S
some support for invoking their existing query solution using the named query facility in
4mH|Fpl^K{/k9ij0the Java Persistence API. We will discuss SQL named queries in Chapter 9.