Combining readOnly and serialize
Now that you understand each of these attributes, it may appear that they overlap
functionality to some degree. The truth is that they simply work very tightly
together. It's important to understand what happens under the hood when you
have different combinations of these attributes. We'll look at all four possible
combinations and analyze what their benefit is (or lack thereof) in table 9.3.
Summary of readOnly and serialize attribute combinations
Tr u e
Fa l s e
Fastest retrieval of cached objects. Returns a shared
instance of the cached objects, which can be problematic
Fast retrieval of cached objects. Retrieves a deep copy of
the cached objects.
Cache is only relevant for the life of the calling thread's
session and cannot be utilized by other threads.
Tr u e
Tr u e
This combination would work the same as read-
Only=false and serialize=true , except that it would
not make any sense semantically.
The default combination of these two attributes is readOnly=true and serial-
ize=false . This combination instructs the cache to pass back the same reference
that is contained within the cache. When using this combination, it is possible to
actually alter the cached object. This can be problematic because the object is
shared globally. All users who access the cached object through the query mapped
statement using the same parameters could possibly retrieve objects that were
inappropriately altered by another session.
When dealing with cached objects that you do want to alter, you should mark
readOnly as false. This will force the cache to return an instance that is specific to
the session. When using this in combination with serialize set to true, you are
able to get a deep copy of the cached object. This isolates the changes of the
retrieved object to the calling session.
Another combination that can be used is to set readOnly as false and serialize
as false. This can be a useful approach, but it's a rare case where it is appropriate.
Setting the two attributes to false requires the cache to produce unique instances
of the requested objects for the calling thread. Since serialize is set to false, it
does not use the deep copy strategy. Instead, the cache is created to be used only
for the life of the session. This means that if you called the same query mapped