EJB--Query Best Practices

上一篇 / 下一篇  2008-05-10 19:16:01 / 个人分类:EJB

Named Queries
;l:bI8XFPOJ G*pZ0
First 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$mLbg#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@V z
cycle with the understanding that the query namespace is global for each persistence unit. CollisionsITPUB个人空间 p RX;p)tRnT U
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.
{q.E'e e#`lN)l|0Report QueriesITPUB个人空间 _ F s+QrS
If you are executing queries that return entities for reporting purposes and have no intention
;Du6l#S^5P r0_ r8M0of modifying the results, consider executing queries using a transaction-scoped entity manager
M/Z&FxM.\0but outside of a transaction. The persistence provider may be able to detect the lack of aITPUB个人空间"d2J2mt_l
transaction and optimize the results for detachment, often by skipping some of the stepsITPUB个人空间SVK`2UwP%S'Tg`]
required to create an interim managed version of the entity results.ITPUB个人空间 vh l5j+XcV q d
Likewise, if an entity is expensive to construct due to eager relationships or a complex
9H\+d.z ~`3E|0table mapping, consider selecting individual entity properties using a projection query instead
cq2xc oi']0of retrieving the full entity result. If all you need is the name and office phone number for 500ITPUB个人空间&KH(@+lK O4?D
employees, selecting only those two fields is likely to be far more efficient than fully constructing
7y/S+|%?'o!]F G1X:w ]01,000 entity instances.

Query Hints
cVp)B SB]F0It is quite likely that vendors will entice you with a variety of hints to enable different performance
H+{-t`~ g!W0optimizations for queries. Query hints may well be an essential tool in meeting your
!eqS J/V{:V0performance expectations. We strongly advise, however, that you resist the urge to embed
0R av6vc#}0query hints in your application code. The ideal location for query hints is in an XML mappingITPUB个人空间T| \9yV%_B$~2wW
file (which we will be describing in Chapter 10), or at the very least as part of a named queryITPUB个人空间)y.Z ` \Nc
definition. Hints are often highly dependent on the target platform. and may well change over
k1I\k'|4hq0time as different aspects of the application impact the overall balance of performance. Keep
hZkE!v*MQ0hints decoupled from your code if at all possible.ITPUB个人空间6V1Q v9@tT9I E*T
Stateless Session Beans
)zG6EA` j d0We tried to demonstrate as many examples as possible in the context of a stateless session bean
9E3W ?c%W8h~ f'f8E0method, as we believe that this is the best way to organize queries in a Java EE application.
Z6flw!C%K!m QQ r}@0Using the stateless session bean has a number of benefits over simply embedding queries all
:hB U5Z&X kI{I0over the place in application code:
:co-~B4g&d`Y)`,j0• Clients can execute queries by invoking an appropriately named business methodITPUB个人空间G0\!s/g8IY^
instead of relying on a cryptic query name or multiple copies of the same query string.ITPUB个人空间9\(lLm;jZ
• Stateless session bean methods can optimize their transaction usage depending onITPUB个人空间 M%J H G'i8]D
whether or not the results need to be managed or detached.
:]{ @ q4L4e0• Using a transaction-scoped persistence context ensures that large numbers of entityITPUB个人空间wX0Dz_u)N3ql
instances don’t remain managed long after they are needed.ITPUB个人空间{&G { Yb1x
• For existing entity bean applications, the stateless session bean is the ideal vehicle for
!h5M/v^ }W0migrating finder queries away from the entity bean home interface. This is not to say that other components are unsuitable locations for queries, but statelessITPUB个人空间l!_2I,z(HW
session beans are a well-established best practice for hosting queries in the Java EE
o6A!cc o2D,cS g l1?o0environment.ITPUB个人空间;P.p,jzIB
Bulk Update and Delete
.~*X:I3M(pSx0If bulk update and delete operations must be used, ensure that they are executed only in an isolated
%WM\4R.[7K-J#Ix0transaction where no other changes are being made. There are many ways in which these
2m{X4G)ERO0queries can negatively impact an active persistence context. Interweaving these queries with
(A+L7U3p,O%[(u ^:v0other non-bulk operations requires careful management by the application.
JHMD6Q2L'K K0Entity versioning and locking requires special consideration when bulk update operationsITPUB个人空间;u!ZFRASEI_2aU
are used. Bulk delete operations can have wide ranging ramifications depending on how wellITPUB个人空间D;WM:oV N!bK
the persistence provider can react and adjust entity caching in response. Therefore we viewITPUB个人空间o"~l2P7Y
bulk update and delete operations as being highly specialized, to be used with care.
gA9r)]8`-B#|0Provider DifferencesITPUB个人空间$qf1}5e'rV+a!`
Take time to become familiar with the SQL that your persistence provider generates for differentITPUB个人空间pC?"mo,Ge_
JPQL queries. Although understanding SQL is not necessary for writing JPQL queries,knowing what happens in response to the various JPQL operations is an essential part of performanceITPUB个人空间*?S7m(ym
tuning. Joins in JPQL are not always explicit, and you may find yourself surprised atITPUB个人空间 d)rmox2J&v
the complex SQL generated for a seemingly simple JPQL query.
%M}(}3mP0The benefits of features such as query paging are also dependent on the approach usedITPUB个人空间yh kZb)w:gJG
by your persistence provider. There are a number of different techniques that can be used to
.Z \*S;G8i b8p0| ~.}0accomplish pagination, many of which suffer from performance and scalability issues.
(]C*o+rf*hr0Because the Java Persistence API can’t dictate a particular approach that will work well in allITPUB个人空间g3GX$x7Q n&m5Js
cases, become familiar with the approach used by your provider and whether or not it is
%N2M!XQ!Qck_(`"vay0configurable.ITPUB个人空间^&Xg ]D
Finally, understanding the provider strategy for when and how often it flushes the persistenceITPUB个人空间$D`V8Hz
context is necessary before looking at optimizations such as changing the flush mode.ITPUB个人空间l)Jou hjp
Depending on the caching architecture and query optimizations used by a provider, changingITPUB个人空间K dj:M#_it!r
the flush mode may or may not make a difference to your application.


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-05-17  
    123
45678910
11121314151617
18192021222324
25262728293031

数据统计

  • 访问量: 38
  • 日志数: 10
  • 建立时间: 2007-12-21
  • 更新时间: 2008-05-16

RSS订阅

Open Toolbar