alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Hibernate example source code file (performance.pot)

This example Hibernate source code file (performance.pot) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Hibernate tags/keywords

cache, cat, for, hibernate, hibernate, if, in, tag, tag, the, the, this, this, you

The Hibernate performance.pot source code

# SOME DESCRIPTIVE TITLE.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: http://bugs.kde.org\n"
"POT-Creation-Date: 2010-07-20 21:02+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <kde-i18n-doc@kde.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: application/x-xml2pot; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#. Tag: title
#: performance.xml:31
#, no-c-format
msgid "Improving performance"
msgstr ""

#. Tag: title
#: performance.xml:34
#, no-c-format
msgid "Fetching strategies"
msgstr ""

#. Tag: para
#: performance.xml:36
#, no-c-format
msgid "Hibernate uses a <emphasis>fetching strategy to retrieve associated objects if the application needs to navigate the association. Fetch strategies can be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query."
msgstr ""

#. Tag: para
#: performance.xml:42
#, no-c-format
msgid "Hibernate3 defines the following fetching strategies:"
msgstr ""

#. Tag: para
#: performance.xml:46
#, no-c-format
msgid "<emphasis>Join fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN."
msgstr ""

#. Tag: para
#: performance.xml:53
#, no-c-format
msgid "<emphasis>Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy=\"false\", this second select will only be executed when you access the association."
msgstr ""

#. Tag: para
#: performance.xml:61
#, no-c-format
msgid "<emphasis>Subselect fetching: a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy=\"false\", this second select will only be executed when you access the association."
msgstr ""

#. Tag: para
#: performance.xml:70
#, no-c-format
msgid "<emphasis>Batch fetching: an optimization strategy for select fetching. Hibernate retrieves a batch of entity instances or collections in a single SELECT by specifying a list of primary or foreign keys."
msgstr ""

#. Tag: para
#: performance.xml:77
#, no-c-format
msgid "Hibernate also distinguishes between:"
msgstr ""

#. Tag: para
#: performance.xml:81
#, no-c-format
msgid "<emphasis>Immediate fetching: an association, collection or attribute is fetched immediately when the owner is loaded."
msgstr ""

#. Tag: para
#: performance.xml:87
#, no-c-format
msgid "<emphasis>Lazy collection fetching: a collection is fetched when the application invokes an operation upon that collection. This is the default for collections."
msgstr ""

#. Tag: para
#: performance.xml:93
#, no-c-format
msgid "<emphasis>\"Extra-lazy\" collection fetching: individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed. It is suitable for large collections."
msgstr ""

#. Tag: para
#: performance.xml:101
#, no-c-format
msgid "<emphasis>Proxy fetching: a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object."
msgstr ""

#. Tag: para
#: performance.xml:107
#, no-c-format
msgid "<emphasis>\"No-proxy\" fetching: a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy; the association is fetched even when only the identifier is accessed. It is also more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary."
msgstr ""

#. Tag: para
#: performance.xml:117
#, no-c-format
msgid "<emphasis>Lazy attribute fetching: an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary."
msgstr ""

#. Tag: para
#: performance.xml:124
#, no-c-format
msgid "We have two orthogonal notions here: <emphasis>when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class."
msgstr ""

#. Tag: title
#: performance.xml:132
#, no-c-format
msgid "Working with lazy associations"
msgstr ""

#. Tag: para
#: performance.xml:134
#, no-c-format
msgid "By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications."
msgstr ""

#. Tag: para
#: performance.xml:138
#, no-c-format
msgid "If you set <literal>hibernate.default_batch_fetch_size, Hibernate will use the batch fetch optimization for lazy fetching. This optimization can also be enabled at a more granular level."
msgstr ""

#. Tag: para
#: performance.xml:142
#, no-c-format
msgid "Please be aware that access to a lazy association outside of the context of an open Hibernate session will result in an exception. For example:"
msgstr ""

#. Tag: programlisting
#: performance.xml:146
#, no-c-format
msgid ""
      "s = sessions.openSession();\n"
      "Transaction tx = s.beginTransaction();\n"
      "            \n"
      "User u = (User) s.createQuery(\"from User u where u.name=:userName\")\n"
      "    .setString(\"userName\", userName).uniqueResult();\n"
      "Map permissions = u.getPermissions();\n"
      "\n"
      "tx.commit();\n"
      "s.close();\n"
      "\n"
      "Integer accessLevel = (Integer) permissions.get(\"accounts\");  // Error!"
msgstr ""

#. Tag: para
#: performance.xml:148
#, no-c-format
msgid "Since the permissions collection was not initialized when the <literal>Session was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects. This can be fixed by moving the code that reads from the collection to just before the transaction is committed."
msgstr ""

#. Tag: para
#: performance.xml:155
#, no-c-format
msgid "Alternatively, you can use a non-lazy collection or association, by specifying <literal>lazy=\"false\" for the association mapping. However, it is intended that lazy initialization be used for almost all collections and associations. If you define too many non-lazy associations in your object model, Hibernate will fetch the entire database into memory in every transaction."
msgstr ""

#. Tag: para
#: performance.xml:162
#, no-c-format
msgid "On the other hand, you can use join fetching, which is non-lazy by nature, instead of select fetching in a particular transaction. We will now explain how to customize the fetching strategy. In Hibernate3, the mechanisms for choosing a fetch strategy are identical for single-valued associations and collections."
msgstr ""

#. Tag: title
#: performance.xml:170
#, no-c-format
msgid "Tuning fetch strategies"
msgstr ""

#. Tag: para
#: performance.xml:172
#, no-c-format
msgid "Select fetching (the default) is extremely vulnerable to N+1 selects problems, so we might want to enable join fetching in the mapping document:"
msgstr ""

#. Tag: programlisting
#: performance.xml:176
#, no-c-format
msgid ""
      "<set name=\"permissions\"\n"
      "            fetch=\"join\">\n"
      "    <key column=\"userId\"/>\n"
      "    <one-to-many class=\"Permission\"/>\n"
      "</set"
msgstr ""

#. Tag: programlisting
#: performance.xml:178
#, no-c-format
msgid "<many-to-one name=\"mother\" class=\"Cat\" fetch=\"join\"/>"
msgstr ""

#. Tag: para
#: performance.xml:180
#, no-c-format
msgid "The <literal>fetch strategy defined in the mapping document affects:"
msgstr ""

#. Tag: para
#: performance.xml:185
#, no-c-format
msgid "retrieval via <literal>get() or load()"
msgstr ""

#. Tag: para
#: performance.xml:190
#, no-c-format
msgid "retrieval that happens implicitly when an association is navigated"
msgstr ""

#. Tag: para
#: performance.xml:195
#, no-c-format
msgid "<literal>Criteria queries"
msgstr ""

#. Tag: para
#: performance.xml:199
#, no-c-format
msgid "HQL queries if <literal>subselect fetching is used"
msgstr ""

#. Tag: para
#: performance.xml:204
#, no-c-format
msgid "Irrespective of the fetching strategy you use, the defined non-lazy graph is guaranteed to be loaded into memory. This might, however, result in several immediate selects being used to execute a particular HQL query."
msgstr ""

#. Tag: para
#: performance.xml:209
#, no-c-format
msgid "Usually, the mapping document is not used to customize fetching. Instead, we keep the default behavior, and override it for a particular transaction, using <literal>left join fetch in HQL. This tells Hibernate to fetch the association eagerly in the first select, using an outer join. In the Criteria query API, you would use setFetchMode(FetchMode.JOIN)."
msgstr ""

#. Tag: para
#: performance.xml:216
#, no-c-format
msgid "If you want to change the fetching strategy used by <literal>get() or load(), you can use a Criteria query. For example:"
msgstr ""

#. Tag: programlisting
#: performance.xml:220
#, no-c-format
msgid ""
      "User user = (User) session.createCriteria(User.class)\n"
      "                .setFetchMode(\"permissions\", FetchMode.JOIN)\n"
      "                .add( Restrictions.idEq(userId) )\n"
      "                .uniqueResult();"
msgstr ""

#. Tag: para
#: performance.xml:222
#, no-c-format
msgid "This is Hibernate's equivalent of what some ORM solutions call a \"fetch plan\"."
msgstr ""

#. Tag: para
#: performance.xml:225
#, no-c-format
msgid "A completely different approach to problems with N+1 selects is to use the second-level cache."
msgstr ""

#. Tag: title
#: performance.xml:230
#, no-c-format
msgid "Single-ended association proxies"
msgstr ""

#. Tag: para
#: performance.xml:232
#, no-c-format
msgid "Lazy fetching for collections is implemented using Hibernate's own implementation of persistent collections. However, a different mechanism is needed for lazy behavior in single-ended associations. The target entity of the association must be proxied. Hibernate implements lazy initializing proxies for persistent objects using runtime bytecode enhancement which is accessed via the CGLIB library."
msgstr ""

#. Tag: para
#: performance.xml:239
#, no-c-format
msgid "At startup, Hibernate3 generates proxies by default for all persistent classes and uses them to enable lazy fetching of <literal>many-to-one and one-to-one associations."
msgstr ""

#. Tag: para
#: performance.xml:244
#, no-c-format
msgid "The mapping file may declare an interface to use as the proxy interface for that class, with the <literal>proxy attribute. By default, Hibernate uses a subclass of the class. The proxied class must implement a default constructor with at least package visibility. This constructor is recommended for all persistent classes."
msgstr ""

#. Tag: para
#: performance.xml:251
#, no-c-format
msgid "There are potential problems to note when extending this approach to polymorphic classes.For example:"
msgstr ""

#. Tag: programlisting
#: performance.xml:254
#, no-c-format
msgid ""
      "<class name=\"Cat\" proxy=\"Cat\">\n"
      "    ......\n"
      "    <subclass name=\"DomesticCat\">\n"
      "        .....\n"
      "    </subclass>\n"
      "</class>"
msgstr ""

#. Tag: para
#: performance.xml:256
#, no-c-format
msgid "Firstly, instances of <literal>Cat will never be castable to DomesticCat, even if the underlying instance is an instance of DomesticCat:"
msgstr ""

#. Tag: programlisting
#: performance.xml:260
#, no-c-format
msgid ""
      "Cat cat = (Cat) session.load(Cat.class, id);  // instantiate a proxy (does not hit the db)\n"
      "if ( cat.isDomesticCat() ) {                  // hit the db to initialize the proxy\n"
      "    DomesticCat dc = (DomesticCat) cat;       // Error!\n"
      "    ....\n"
      "}"
msgstr ""

#. Tag: para
#: performance.xml:262
#, no-c-format
msgid "Secondly, it is possible to break proxy <literal>==:"
msgstr ""

#. Tag: programlisting
#: performance.xml:265
#, no-c-format
msgid ""
      "Cat cat = (Cat) session.load(Cat.class, id);            // instantiate a Cat proxy\n"
      "DomesticCat dc = \n"
      "        (DomesticCat) session.load(DomesticCat.class, id);  // acquire new DomesticCat proxy!\n"
      "System.out.println(cat==dc);                            // false"
msgstr ""

#. Tag: para
#: performance.xml:267
#, no-c-format
msgid "However, the situation is not quite as bad as it looks. Even though we now have two references to different proxy objects, the underlying instance will still be the same object:"
msgstr ""

#. Tag: programlisting
#: performance.xml:271
#, no-c-format
msgid ""
      "cat.setWeight(11.0);  // hit the db to initialize the proxy\n"
      "System.out.println( dc.getWeight() );  // 11.0"
msgstr ""

#. Tag: para
#: performance.xml:273
#, no-c-format
msgid "Third, you cannot use a CGLIB proxy for a <literal>final class or a class with any final methods."
msgstr ""

#. Tag: para
#: performance.xml:276
#, no-c-format
msgid "Finally, if your persistent object acquires any resources upon instantiation (e.g. in initializers or default constructor), then those resources will also be acquired by the proxy. The proxy class is an actual subclass of the persistent class."
msgstr ""

#. Tag: para
#: performance.xml:281
#, no-c-format
msgid "These problems are all due to fundamental limitations in Java's single inheritance model. To avoid these problems your persistent classes must each implement an interface that declares its business methods. You should specify these interfaces in the mapping file where <literal>CatImpl implements the interface Cat and DomesticCatImpl implements the interface DomesticCat. For example:"
msgstr ""

#. Tag: programlisting
#: performance.xml:289
#, no-c-format
msgid ""
      "<class name=\"CatImpl\" proxy=\"Cat\">\n"
      "    ......\n"
      "    <subclass name=\"DomesticCatImpl\" proxy=\"DomesticCat\">\n"
      "        .....\n"
      "    </subclass>\n"
      "</class>"
msgstr ""

#. Tag: para
#: performance.xml:291
#, no-c-format
msgid "Then proxies for instances of <literal>Cat and DomesticCat can be returned by load() or iterate()."
msgstr ""

#. Tag: programlisting
#: performance.xml:295
#, no-c-format
msgid ""
      "Cat cat = (Cat) session.load(CatImpl.class, catid);\n"
      "Iterator iter = session.createQuery(\"from CatImpl as cat where cat.name='fritz'\").iterate();\n"
      "Cat fritz = (Cat) iter.next();"
msgstr ""

#. Tag: title
#: performance.xml:298
#, no-c-format
msgid "Note"
msgstr ""

#. Tag: para
#: performance.xml:300
#, no-c-format
msgid "<literal>list() does not usually return proxies."
msgstr ""

#. Tag: para
#: performance.xml:304
#, no-c-format
msgid "Relationships are also lazily initialized. This means you must declare any properties to be of type <literal>Cat, not CatImpl."
msgstr ""

#. Tag: para
#: performance.xml:308
#, no-c-format
msgid "Certain operations do <emphasis>not require proxy initialization:"
msgstr ""

#. Tag: para
#: performance.xml:313
#, no-c-format
msgid "<literal>equals(): if the persistent class does not override equals()"
msgstr ""

#. Tag: para
#: performance.xml:318
#, no-c-format
msgid "<literal>hashCode(): if the persistent class does not override hashCode()"
msgstr ""

#. Tag: para
#: performance.xml:323
#, no-c-format
msgid "The identifier getter method"
msgstr ""

#. Tag: para
#: performance.xml:327
#, no-c-format
msgid "Hibernate will detect persistent classes that override <literal>equals() or hashCode()."
msgstr ""

#. Tag: para
#: performance.xml:330
#, no-c-format
msgid "By choosing <literal>lazy=\"no-proxy\" instead of the default lazy=\"proxy\", you can avoid problems associated with typecasting. However, buildtime bytecode instrumentation is required, and all operations will result in immediate proxy initialization."
msgstr ""

#. Tag: title
#: performance.xml:338
#, no-c-format
msgid "Initializing collections and proxies"
msgstr ""

#. Tag: para
#: performance.xml:340
#, no-c-format
msgid "A <literal>LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, i.e., when the entity owning the collection or having the reference to the proxy is in the detached state."
msgstr ""

#. Tag: para
#: performance.xml:346
#, no-c-format
msgid "Sometimes a proxy or collection needs to be initialized before closing the <literal>Session. You can force initialization by calling cat.getSex() or cat.getKittens().size(), for example. However, this can be confusing to readers of the code and it is not convenient for generic code."
msgstr ""

#. Tag: para
#: performance.xml:353
#, no-c-format
msgid "The static methods <literal>Hibernate.initialize() and Hibernate.isInitialized(), provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(cat) will force the initialization of a proxy, cat, as long as its Session is still open. Hibernate.initialize( cat.getKittens() ) has a similar effect for the collection of kittens."
msgstr ""

#. Tag: para
#: performance.xml:362
#, no-c-format
msgid "Another option is to keep the <literal>Session open until all required collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized. There are two basic ways to deal with this issue:"
msgstr ""

#. Tag: para
#: performance.xml:372
#, no-c-format
msgid "In a web-based application, a servlet filter can be used to close the <literal>Session only at the end of a user request, once the rendering of the view is complete (the Open Session in View pattern). Of course, this places heavy demands on the correctness of the exception handling of your application infrastructure. It is vitally important that the Session is closed and the transaction ended before returning to the user, even when an exception occurs during rendering of the view. See the Hibernate Wiki for examples of this \"Open Session in View\" pattern."
msgstr ""

#. Tag: para
#: performance.xml:385
#, no-c-format
msgid "In an application with a separate business tier, the business logic must \"prepare\" all collections that the web tier needs before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls <literal>Hibernate.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode.JOIN in Criteria. This is usually easier if you adopt the Command pattern instead of a Session Facade."
msgstr ""

#. Tag: para
#: performance.xml:401
#, no-c-format
msgid "You can also attach a previously loaded object to a new <literal>Session with merge() or lock() before accessing uninitialized collections or other proxies. Hibernate does not, and certainly should not, do this automatically since it would introduce impromptu transaction semantics."
msgstr ""

#. Tag: para
#: performance.xml:410
#, no-c-format
msgid "Sometimes you do not want to initialize a large collection, but still need some information about it, like its size, for example, or a subset of the data."
msgstr ""

#. Tag: para
#: performance.xml:414
#, no-c-format
msgid "You can use a collection filter to get the size of a collection without initializing it:"
msgstr ""

#. Tag: programlisting
#: performance.xml:417
#, no-c-format
msgid "( (Integer) s.createFilter( collection, \"select count(*)\" ).list().get(0) ).intValue()"
msgstr ""

#. Tag: para
#: performance.xml:419
#, no-c-format
msgid "The <literal>createFilter() method is also used to efficiently retrieve subsets of a collection without needing to initialize the whole collection:"
msgstr ""

#. Tag: programlisting
#: performance.xml:423
#, no-c-format
msgid "s.createFilter( lazyCollection, \"\").setFirstResult(0).setMaxResults(10).list();"
msgstr ""

#. Tag: title
#: performance.xml:427
#, no-c-format
msgid "Using batch fetching"
msgstr ""

#. Tag: para
#: performance.xml:429
#, no-c-format
msgid "Using batch fetching, Hibernate can load several uninitialized proxies if one proxy is accessed. Batch fetching is an optimization of the lazy select fetching strategy. There are two ways you can configure batch fetching: on the class level and the collection level."
msgstr ""

#. Tag: para
#: performance.xml:434
#, no-c-format
msgid "Batch fetching for classes/entities is easier to understand. Consider the following example: at runtime you have 25 <literal>Cat instances loaded in a Session, and each Cat has a reference to its owner, a Person. The Person class is mapped with a proxy, lazy=\"true\". If you now iterate through all cats and call getOwner() on each, Hibernate will, by default, execute 25 SELECT statements to retrieve the proxied owners. You can tune this behavior by specifying a batch-size in the mapping of Person:"
msgstr ""

#. Tag: programlisting
#: performance.xml:447
#, no-c-format
msgid "<class name=\"Person\" batch-size=\"10\">...</class>"
msgstr ""

#. Tag: para
#: performance.xml:449
#, no-c-format
msgid "Hibernate will now execute only three queries: the pattern is 10, 10, 5."
msgstr ""

#. Tag: para
#: performance.xml:452
#, no-c-format
msgid "You can also enable batch fetching of collections. For example, if each <literal>Person has a lazy collection of Cats, and 10 persons are currently loaded in the Session, iterating through all persons will generate 10 SELECTs, one for every call to getCats(). If you enable batch fetching for the cats collection in the mapping of Person, Hibernate can pre-fetch collections:"
msgstr ""

#. Tag: programlisting
#: performance.xml:461
#, no-c-format
msgid ""
      "<class name=\"Person\">\n"
      "    <set name=\"cats\" batch-size=\"3\">\n"
      "        ...\n"
      "    </set>\n"
      "</class>"
msgstr ""

#. Tag: para
#: performance.xml:463
#, no-c-format
msgid "With a <literal>batch-size of 3, Hibernate will load 3, 3, 3, 1 collections in four SELECTs. Again, the value of the attribute depends on the expected number of uninitialized collections in a particular Session."
msgstr ""

#. Tag: para
#: performance.xml:468
#, no-c-format
msgid "Batch fetching of collections is particularly useful if you have a nested tree of items, i.e. the typical bill-of-materials pattern. However, a <emphasis>nested set or a materialized path might be a better option for read-mostly trees."
msgstr ""

#. Tag: title
#: performance.xml:475
#, no-c-format
msgid "Using subselect fetching"
msgstr ""

#. Tag: para
#: performance.xml:477
#, no-c-format
msgid "If one lazy collection or single-valued proxy has to be fetched, Hibernate will load all of them, re-running the original query in a subselect. This works in the same way as batch-fetching but without the piecemeal loading."
msgstr ""

#. Tag: title
#: performance.xml:486
#, no-c-format
msgid "Fetch profiles"
msgstr ""

#. Tag: para
#: performance.xml:488
#, no-c-format
msgid "Another way to affect the fetching strategy for loading associated objects is through something called a fetch profile, which is a named configuration associated with the <interfacename>org.hibernate.SessionFactory but enabled, by name, on the org.hibernate.Session. Once enabled on a org.hibernate.Session, the fetch profile will be in affect for that org.hibernate.Session until it is explicitly disabled."
msgstr ""

#. Tag: para
#: performance.xml:498
#, no-c-format
msgid "So what does that mean? Well lets explain that by way of an example which show the different available approaches to configure a fetch profile:"
msgstr ""

#. Tag: title
#: performance.xml:503
#, no-c-format
msgid "Specifying a fetch profile using <classname>@FetchProfile"
msgstr ""

#. Tag: programlisting
#: performance.xml:506
#, no-c-format
msgid ""
      "@Entity\n"
      "@FetchProfile(name = \"customer-with-orders\", fetchOverrides = {\n"
      "   @FetchProfile.FetchOverride(entity = Customer.class, association = \"orders\", mode = FetchMode.JOIN)\n"
      "})\n"
      "public class Customer {\n"
      "   @Id\n"
      "   @GeneratedValue\n"
      "   private long id;\n"
      "\n"
      "   private String name;\n"
      "\n"
      "   private long customerNumber;\n"
      "\n"
      "   @OneToMany\n"
      "   private Set<Order> orders;\n"
      "\n"
      "   // standard getter/setter\n"
      "   ...\n"
      "}"
msgstr ""

#. Tag: title
#: performance.xml:510
#, no-c-format
msgid "Specifying a fetch profile using <literal><fetch-profile> outside <class> node"
msgstr ""

#. Tag: programlisting
#: performance.xml:514
#, no-c-format
msgid ""
      "<hibernate-mapping>\n"
      "    <class name=\"Customer\">\n"
      "        ...\n"
      "        <set name=\"orders\" inverse=\"true\">\n"
      "            <key column=\"cust_id\"/>\n"
      "            <one-to-many class=\"Order\"/>\n"
      "        </set>\n"
      "    </class>\n"
      "    <class name=\"Order\">\n"
      "        ...\n"
      "    </class>\n"
      "    <fetch-profile name=\"customer-with-orders\">\n"
      "        <fetch entity=\"Customer\" association=\"orders\" style=\"join\"/>\n"
      "    </fetch-profile>\n"
      "</hibernate-mapping>"
msgstr ""

#. Tag: title
#: performance.xml:518
#, no-c-format
msgid "Specifying a fetch profile using <literal><fetch-profile> inside <class> node"
msgstr ""

#. Tag: programlisting
#: performance.xml:522
#, no-c-format
msgid ""
      "<hibernate-mapping>\n"
      "    <class name=\"Customer\">\n"
      "        ...\n"
      "        <set name=\"orders\" inverse=\"true\">\n"
      "            <key column=\"cust_id\"/>\n"
      "            <one-to-many class=\"Order\"/>\n"
      "        </set>\n"
      "        <fetch-profile name=\"customer-with-orders\">\n"
      "            <fetch association=\"orders\" style=\"join\"/>\n"
      "        </fetch-profile>\n"
      "    </class>\n"
      "    <class name=\"Order\">\n"
      "        ...\n"
      "    </class>\n"
      "</hibernate-mapping>"
msgstr ""

#. Tag: para
#: performance.xml:525
#, no-c-format
msgid "Now normally when you get a reference to a particular customer, that customer's set of orders will be lazy meaning we will not yet have loaded those orders from the database. Normally this is a good thing. Now lets say that you have a certain use case where it is more efficient to load the customer and their orders together. One way certainly is to use \"dynamic fetching\" strategies via an HQL or criteria queries. But another option is to use a fetch profile to achieve that. The following code will load both the customer <emphasis>andtheir orders:"
msgstr ""

#. Tag: title
#: performance.xml:536
#, no-c-format
msgid "Activating a fetch profile for a given <classname>Session"
msgstr ""

#. Tag: programlisting
#: performance.xml:539
#, no-c-format
msgid ""
      "Session session = ...;\n"
      "session.enableFetchProfile( \"customer-with-orders\" );  // name matches from mapping\n"
      "Customer customer = (Customer) session.get( Customer.class, customerId );"
msgstr ""

#. Tag: para
#: performance.xml:543
#, no-c-format
msgid "<classname>@FetchProfile definitions are global and it does not matter on which class you place them. You can place the @FetchProfile annotation either onto a class or package (package-info.java). In order to define multiple fetch profiles for the same class or package @FetchProfiles can be used."
msgstr ""

#. Tag: para
#: performance.xml:551
#, no-c-format
msgid "Currently only join style fetch profiles are supported, but they plan is to support additional styles. See <ulink url=\"http://opensource.atlassian.com/projects/hibernate/browse/HHH-3414\">HHH-3414 for details."
msgstr ""

#. Tag: title
#: performance.xml:558
#, no-c-format
msgid "Using lazy property fetching"
msgstr ""

#. Tag: para
#: performance.xml:560
#, no-c-format
msgid "Hibernate3 supports the lazy fetching of individual properties. This optimization technique is also known as <emphasis>fetch groups. Please note that this is mostly a marketing feature; optimizing row reads is much more important than optimization of column reads. However, only loading some properties of a class could be useful in extreme cases. For example, when legacy tables have hundreds of columns and the data model cannot be improved."
msgstr ""

#. Tag: para
#: performance.xml:568
#, no-c-format
msgid "To enable lazy property loading, set the <literal>lazy attribute on your particular property mappings:"
msgstr ""

#. Tag: programlisting
#: performance.xml:571
#, no-c-format
msgid ""
      "<class name=\"Document\">\n"
      "       <id name=\"id\">\n"
      "        <generator class=\"native\"/>\n"
      "    </id>\n"
      "    <property name=\"name\" not-null=\"true\" length=\"50\"/>\n"
      "    <property name=\"summary\" not-null=\"true\" length=\"200\" lazy=\"true\"/>\n"
      "    <property name=\"text\" not-null=\"true\" length=\"2000\" lazy=\"true\"/>\n"
      "</class>"
msgstr ""

#. Tag: para
#: performance.xml:573
#, no-c-format
msgid "Lazy property loading requires buildtime bytecode instrumentation. If your persistent classes are not enhanced, Hibernate will ignore lazy property settings and return to immediate fetching."
msgstr ""

#. Tag: para
#: performance.xml:577
#, no-c-format
msgid "For bytecode instrumentation, use the following Ant task:"
msgstr ""

#. Tag: programlisting
#: performance.xml:579
#, no-c-format
msgid ""
      "<target name=\"instrument\" depends=\"compile\">\n"
      "    <taskdef name=\"instrument\" classname=\"org.hibernate.tool.instrument.InstrumentTask\">\n"
      "        <classpath path=\"${jar.path}\"/>\n"
      "        <classpath path=\"${classes.dir}\"/>\n"
      "        <classpath refid=\"lib.class.path\"/>\n"
      "    </taskdef>\n"
      "\n"
      "    <instrument verbose=\"true\">\n"
      "        <fileset dir=\"${testclasses.dir}/org/hibernate/auction/model\">\n"
      "            <include name=\"*.class\"/>\n"
      "        </fileset>\n"
      "    </instrument>\n"
      "</target>"
msgstr ""

#. Tag: para
#: performance.xml:581
#, no-c-format
msgid "A different way of avoiding unnecessary column reads, at least for read-only transactions, is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a preferred solution."
msgstr ""

#. Tag: para
#: performance.xml:586
#, no-c-format
msgid "You can force the usual eager fetching of properties using <literal>fetch all properties in HQL."
msgstr ""

#. Tag: title
#: performance.xml:592
#, no-c-format
msgid "The Second Level Cache"
msgstr ""

#. Tag: para
#: performance.xml:594
#, no-c-format
msgid "A Hibernate <literal>Session is a transaction-level cache of persistent data. It is possible to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis. You can even plug in a clustered cache. Be aware that caches are not aware of changes made to the persistent store by another application. They can, however, be configured to regularly expire cached data."
msgstr ""

#. Tag: para
#: performance.xml:602
#, no-c-format
msgid "You have the option to tell Hibernate which caching implementation to use by specifying the name of a class that implements <literal>org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate is bundled with a number of built-in integrations with the open-source cache providers that are listed in . You can also implement your own and plug it in as outlined above. Note that versions prior to Hibernate 3.2 use EhCache as the default cache provider."
msgstr ""

#. Tag: title
#: performance.xml:613
#, no-c-format
msgid "Cache Providers"
msgstr ""

#. Tag: entry
#: performance.xml:628 performance.xml:976
#, no-c-format
msgid "Cache"
msgstr ""

#. Tag: entry
#: performance.xml:630
#, no-c-format
msgid "Provider class"
msgstr ""

#. Tag: entry
#: performance.xml:632
#, no-c-format
msgid "Type"
msgstr ""

#. Tag: entry
#: performance.xml:634
#, no-c-format
msgid "Cluster Safe"
msgstr ""

#. Tag: entry
#: performance.xml:636
#, no-c-format
msgid "Query Cache Supported"
msgstr ""

#. Tag: entry
#: performance.xml:642 performance.xml:990
#, no-c-format
msgid "Hashtable (not intended for production use)"
msgstr ""

#. Tag: literal
#: performance.xml:644
#, no-c-format
msgid "org.hibernate.cache.HashtableCacheProvider"
msgstr ""

#. Tag: entry
#: performance.xml:646
#, no-c-format
msgid "memory"
msgstr ""

#. Tag: entry
#: performance.xml:650 performance.xml:662 performance.xml:674 performance.xml:992 performance.xml:994 performance.xml:996 performance.xml:1004 performance.xml:1006 performance.xml:1008 performance.xml:1016 performance.xml:1018 performance.xml:1020 performance.xml:1028 performance.xml:1030 performance.xml:1040 performance.xml:1046 performance.xml:1052 performance.xml:1058
#, no-c-format
msgid "<entry>yes"
msgstr ""

#. Tag: entry
#: performance.xml:654 performance.xml:1002
#, no-c-format
msgid "EHCache"
msgstr ""

#. Tag: literal
#: performance.xml:656
#, no-c-format
msgid "org.hibernate.cache.EhCacheProvider"
msgstr ""

#. Tag: entry
#: performance.xml:658 performance.xml:670
#, no-c-format
msgid "memory, disk"
msgstr ""

#. Tag: entry
#: performance.xml:666 performance.xml:1014
#, no-c-format
msgid "OSCache"
msgstr ""

#. Tag: literal
#: performance.xml:668
#, no-c-format
msgid "org.hibernate.cache.OSCacheProvider"
msgstr ""

#. Tag: entry
#: performance.xml:678 performance.xml:1026
#, no-c-format
msgid "SwarmCache"
msgstr ""

#. Tag: literal
#: performance.xml:680
#, no-c-format
msgid "org.hibernate.cache.SwarmCacheProvider"
msgstr ""

#. Tag: entry
#: performance.xml:682
#, no-c-format
msgid "clustered (ip multicast)"
msgstr ""

#. Tag: entry
#: performance.xml:684
#, no-c-format
msgid "yes (clustered invalidation)"
msgstr ""

#. Tag: entry
#: performance.xml:690 performance.xml:1038
#, no-c-format
msgid "JBoss Cache 1.x"
msgstr ""

#. Tag: literal
#: performance.xml:692
#, no-c-format
msgid "org.hibernate.cache.TreeCacheProvider"
msgstr ""

#. Tag: entry
#: performance.xml:694 performance.xml:706
#, no-c-format
msgid "clustered (ip multicast), transactional"
msgstr ""

#. Tag: entry
#: performance.xml:696
#, no-c-format
msgid "yes (replication)"
msgstr ""

#. Tag: entry
#: performance.xml:698 performance.xml:710
#, no-c-format
msgid "yes (clock sync req.)"
msgstr ""

#. Tag: entry
#: performance.xml:702 performance.xml:1050
#, no-c-format
msgid "JBoss Cache 2"
msgstr ""

#. Tag: literal
#: performance.xml:704
#, no-c-format
msgid "org.hibernate.cache.jbc.JBossCacheRegionFactory"
msgstr ""

#. Tag: entry
#: performance.xml:708
#, no-c-format
msgid "yes (replication or invalidation)"
msgstr ""

#. Tag: title
#: performance.xml:717
#, no-c-format
msgid "Cache mappings"
msgstr ""

#. Tag: para
#: performance.xml:719
#, no-c-format
msgid "As we have done in previous chapters we are looking at the two different possibiltites to configure caching. First configuration via annotations and then via Hibernate mapping files."
msgstr ""

#. Tag: para
#: performance.xml:723
#, no-c-format
msgid "By default, entities are not part of the second level cache and we recommend you to stick to this setting. However, you can override this by setting the <literal>shared-cache-mode element in your persistence.xml file or by using the javax.persistence.sharedCache.mode property in your configuration. The following values are possible:"
msgstr ""

#. Tag: para
#: performance.xml:732
#, no-c-format
msgid "<literal>ENABLE_SELECTIVE (Default and recommended value): entities are not cached unless explicitly marked as cacheable."
msgstr ""

#. Tag: para
#: performance.xml:738
#, no-c-format
msgid "<literal>DISABLE_SELECTIVE: entities are cached unless explicitly marked as not cacheable."
msgstr ""

#. Tag: para
#: performance.xml:743
#, no-c-format
msgid "<literal>ALL: all entities are always cached even if marked as non cacheable."
msgstr ""

#. Tag: para
#: performance.xml:748
#, no-c-format
msgid "<literal>NONE: no entity are cached even if marked as cacheable. This option can make sense to disable second-level cache altogether."
msgstr ""

#. Tag: para
#: performance.xml:754
#, no-c-format
msgid "The cache concurrency strategy used by default can be set globaly via the <literal>hibernate.cache.default_cache_concurrency_strategy configuration property. The values for this property are:"
msgstr ""

#. Tag: literal
#: performance.xml:761
#, no-c-format
msgid "<literal>read-only"
msgstr ""

#. Tag: literal
#: performance.xml:765
#, no-c-format
msgid "<literal>read-write"
msgstr ""

#. Tag: literal
#: performance.xml:769
#, no-c-format
msgid "<literal>nonstrict-read-write"
msgstr ""

#. Tag: literal
#: performance.xml:773
#, no-c-format
msgid "<literal>transactional"
msgstr ""

#. Tag: para
#: performance.xml:778
#, no-c-format
msgid "It is recommended to define the cache concurrency strategy per entity rather than using a global one. Use the <classname>@org.hibernate.annotations.Cache annotation for that."
msgstr ""

#. Tag: title
#: performance.xml:785
#, no-c-format
msgid "Definition of cache concurrency strategy via <classname>@Cache"
msgstr ""

#. Tag: programlisting
#: performance.xml:788
#, no-c-format
msgid ""
      "@Entity \n"
      "@Cacheable\n"
      "@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n"
      "public class Forest { ... }"
msgstr ""

#. Tag: para
#: performance.xml:791
#, no-c-format
msgid "Hibernate also let's you cache the content of a collection or the identifiers if the collection contains other entities. Use the <classname>@Cache annotation on the collection property."
msgstr ""

#. Tag: title
#: performance.xml:797
#, no-c-format
msgid "Caching collections using annotations"
msgstr ""

#. Tag: programlisting
#: performance.xml:799
#, no-c-format
msgid ""
      "@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)\n"
      "@JoinColumn(name=\"CUST_ID\")\n"
      "@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n"
      "public SortedSet<Ticket> getTickets() {\n"
      "    return tickets;\n"
      "}"
msgstr ""

#. Tag: para
#: performance.xml:802
#, no-c-format
msgid "shows the<literal> @org.hibernate.annotations.Cache annotations with its attributes. It allows you to define the caching strategy and region of a given second level cache."
msgstr ""

#. Tag: title
#: performance.xml:808
#, no-c-format
msgid "<classname>@Cache annotation with attributes"
msgstr ""

#. Tag: programlisting
#: performance.xml:820
#, no-c-format
msgid ""
      "@Cache(\n"
      "    CacheConcurrencyStrategy usage();\n"
      "    String region() default \"\";\n"
      "    String include() default \"all\";\n"
      ")"
msgstr ""

#. Tag: para
#: performance.xml:824
#, no-c-format
msgid "usage: the given cache concurrency strategy (NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)"
msgstr ""

#. Tag: para
#: performance.xml:830
#, no-c-format
msgid "region (optional): the cache region (default to the fqcn of the class or the fq role name of the collection)"
msgstr ""

#. Tag: para
#: performance.xml:835
#, no-c-format
msgid "<literal>include (optional): all to include all properties, non-lazy to only include non lazy properties (default all)."
msgstr ""

#. Tag: para
#: performance.xml:843
#, no-c-format
msgid "Let's now take a look at Hibernate mapping files. There the <literal><cache> element of a class or collection mapping is used to configure the second level cache. Looking at  the parallels to anotations is obvious."
msgstr ""

#. Tag: title
#: performance.xml:850
#, no-c-format
msgid "The Hibernate <literal><cache> mapping element"
msgstr ""

#. Tag: programlisting
#: performance.xml:862
#, no-c-format
msgid ""
      "<cache\n"
      "    usage=\"transactional|read-write|nonstrict-read-write|read-only\"\n"
      "    region=\"RegionName\"\n"
      "    include=\"all|non-lazy\"\n"
      "/>"
msgstr ""

#. Tag: para
#: performance.xml:866
#, no-c-format
msgid "<literal>usage (required) specifies the caching strategy: transactional, read-write, nonstrict-read-write or read-only"
msgstr ""

#. Tag: para
#: performance.xml:874
#, no-c-format
msgid "<literal>region (optional: defaults to the class or collection role name): specifies the name of the second level cache region"
msgstr ""

#. Tag: para
#: performance.xml:880
#, no-c-format
msgid "<literal>include (optional: defaults to all) non-lazy: specifies that properties of the entity mapped with lazy=\"true\" cannot be cached when attribute-level lazy fetching is enabled"
msgstr ""

#. Tag: para
#: performance.xml:890
#, no-c-format
msgid "Alternatively to <literal><cache>, you can use <class-cache> and <collection-cache> elements in hibernate.cfg.xml."
msgstr ""

#. Tag: para
#: performance.xml:895
#, no-c-format
msgid "Let's now have a closer look at the different usage strategies"
msgstr ""

#. Tag: title
#: performance.xml:900
#, no-c-format
msgid "Strategy: read only"
msgstr ""

#. Tag: para
#: performance.xml:902
#, no-c-format
msgid "If your application needs to read, but not modify, instances of a persistent class, a <literal>read-only cache can be used. This is the simplest and optimal performing strategy. It is even safe for use in a cluster."
msgstr ""

#. Tag: title
#: performance.xml:909
#, no-c-format
msgid "Strategy: read/write"
msgstr ""

#. Tag: para
#: performance.xml:911
#, no-c-format
msgid "If the application needs to update data, a <literal>read-write cache might be appropriate. This cache strategy should never be used if serializable transaction isolation level is required. If the cache is used in a JTA environment, you must specify the property hibernate.transaction.manager_lookup_class and naming a strategy for obtaining the JTA TransactionManager. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called. If you want to use this strategy in a cluster, you should ensure that the underlying cache implementation supports locking. The built-in cache providers do not support locking."
msgstr ""

#. Tag: title
#: performance.xml:927
#, no-c-format
msgid "Strategy: nonstrict read/write"
msgstr ""

#. Tag: para
#: performance.xml:929
#, no-c-format
msgid "If the application only occasionally needs to update data (i.e. if it is extremely unlikely that two transactions would try to update the same item simultaneously), and strict transaction isolation is not required, a <literal>nonstrict-read-write cache might be appropriate. If the cache is used in a JTA environment, you must specify hibernate.transaction.manager_lookup_class. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called."
msgstr ""

#. Tag: title
#: performance.xml:941
#, no-c-format
msgid "Strategy: transactional"
msgstr ""

#. Tag: para
#: performance.xml:943
#, no-c-format
msgid "The <literal>transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache can only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class."
msgstr ""

#. Tag: title
#: performance.xml:950
#, no-c-format
msgid "Cache-provider/concurrency-strategy compatibility"
msgstr ""

#. Tag: para
#: performance.xml:953
#, no-c-format
msgid "None of the cache providers support all of the cache concurrency strategies."
msgstr ""

#. Tag: para
#: performance.xml:957
#, no-c-format
msgid "The following table shows which providers are compatible with which concurrency strategies."
msgstr ""

#. Tag: title
#: performance.xml:961
#, no-c-format
msgid "Cache Concurrency Strategy Support"
msgstr ""

#. Tag: entry
#: performance.xml:978
#, no-c-format
msgid "<entry>read-only"
msgstr ""

#. Tag: entry
#: performance.xml:980
#, no-c-format
msgid "<entry>nonstrict-read-write"
msgstr ""

#. Tag: entry
#: performance.xml:982
#, no-c-format
msgid "<entry>read-write"
msgstr ""

#. Tag: entry
#: performance.xml:984
#, no-c-format
msgid "<entry>transactional"
msgstr ""

#. Tag: title
#: performance.xml:1067
#, no-c-format
msgid "Managing the caches"
msgstr ""

#. Tag: para
#: performance.xml:1069
#, no-c-format
msgid "Whenever you pass an object to <literal>save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session."
msgstr ""

#. Tag: para
#: performance.xml:1076
#, no-c-format
msgid "When <literal>flush() is subsequently called, the state of that object will be synchronized with the database. If you do not want this synchronization to occur, or if you are processing a huge number of objects and need to manage memory efficiently, the evict() method can be used to remove the object and its collections from the first-level cache."
msgstr ""

#. Tag: title
#: performance.xml:1084
#, no-c-format
msgid "Explcitly evicting a cached instance from the first level cache using <methodname>Session.evict()"
msgstr ""

#. Tag: programlisting
#: performance.xml:1087
#, no-c-format
msgid ""
      "ScrollableResult cats = sess.createQuery(\"from Cat as cat\").scroll(); //a huge result set\n"
      "while ( cats.next() ) {\n"
      "    Cat cat = (Cat) cats.get(0);\n"
      "    doSomethingWithACat(cat);\n"
      "    sess.evict(cat);\n"
      "}"
msgstr ""

#. Tag: para
#: performance.xml:1090
#, no-c-format
msgid "The <literal>Session also provides a contains() method to determine if an instance belongs to the session cache."
msgstr ""

#. Tag: para
#: performance.xml:1094
#, no-c-format
msgid "To evict all objects from the session cache, call <literal>Session.clear()"
msgstr ""

#. Tag: para
#: performance.xml:1097
#, no-c-format
msgid "For the second-level cache, there are methods defined on <literal>SessionFactory for evicting the cached state of an instance, entire class, collection instance or entire collection role."
msgstr ""

#. Tag: title
#: performance.xml:1103
#, no-c-format
msgid "Second-level cache eviction via <methodname>SessionFactoty.evict() and SessionFacyory.evictCollection()"
msgstr ""

#. Tag: programlisting
#: performance.xml:1107
#, no-c-format
msgid ""
      "sessionFactory.evict(Cat.class, catId); //evict a particular Cat\n"
      "sessionFactory.evict(Cat.class);  //evict all Cats\n"
      "sessionFactory.evictCollection(\"Cat.kittens\", catId); //evict a particular collection of kittens\n"
      "sessionFactory.evictCollection(\"Cat.kittens\"); //evict all kitten collections"
msgstr ""

#. Tag: para
#: performance.xml:1110
#, no-c-format
msgid "The <literal>CacheMode controls how a particular session interacts with the second-level cache:"
msgstr ""

#. Tag: para
#: performance.xml:1115
#, no-c-format
msgid "<literal>CacheMode.NORMAL: will read items from and write items to the second-level cache"
msgstr ""

#. Tag: para
#: performance.xml:1120
#, no-c-format
msgid "<literal>CacheMode.GET: will read items from the second-level cache. Do not write to the second-level cache except when updating data"
msgstr ""

#. Tag: para
#: performance.xml:1126
#, no-c-format
msgid "<literal>CacheMode.PUT: will write items to the second-level cache. Do not read from the second-level cache"
msgstr ""

#. Tag: para
#: performance.xml:1131
#, no-c-format
msgid "<literal>CacheMode.REFRESH: will write items to the second-level cache. Do not read from the second-level cache. Bypass the effect of hibernate.cache.use_minimal_puts forcing a refresh of the second-level cache for all items read from the database"
msgstr ""

#. Tag: para
#: performance.xml:1139
#, no-c-format
msgid "To browse the contents of a second-level or query cache region, use the <literal>Statistics API:"
msgstr ""

#. Tag: title
#: performance.xml:1143
#, no-c-format
msgid "Browsing the second-level cache entries via the <classname>Statistics API"
msgstr ""

#. Tag: programlisting
#: performance.xml:1146
#, no-c-format
msgid ""
      "Map cacheEntries = sessionFactory.getStatistics()\n"
      "        .getSecondLevelCacheStatistics(regionName)\n"
      "        .getEntries();"
msgstr ""

#. Tag: para
#: performance.xml:1149
#, no-c-format
msgid "You will need to enable statistics and, optionally, force Hibernate to keep the cache entries in a more readable format:"
msgstr ""

#. Tag: title
#: performance.xml:1153
#, no-c-format
msgid "Enabling Hibernate statistics"
msgstr ""

#. Tag: programlisting
#: performance.xml:1155
#, no-c-format
msgid ""
      "hibernate.generate_statistics true\n"
      "hibernate.cache.use_structured_entries true"
msgstr ""

#. Tag: title
#: performance.xml:1160
#, no-c-format
msgid "The Query Cache"
msgstr ""

#. Tag: para
#: performance.xml:1162
#, no-c-format
msgid "Query result sets can also be cached. This is only useful for queries that are run frequently with the same parameters."
msgstr ""

#. Tag: title
#: performance.xml:1166
#, no-c-format
msgid "Enabling query caching"
msgstr ""

#. Tag: para
#: performance.xml:1168
#, no-c-format
msgid "Caching of query results introduces some overhead in terms of your applications normal transactional processing. For example, if you cache results of a query against Person Hibernate will need to keep track of when those results should be invalidated because changes have been committed against Person. That, coupled with the fact that most applications simply gain no benefit from caching query results, leads Hibernate to disable caching of query results by default. To use query caching, you will first need to enable the query cache:"
msgstr ""

#. Tag: programlisting
#: performance.xml:1177
#, no-c-format
msgid "hibernate.cache.use_query_cache true"
msgstr ""

#. Tag: para
#: performance.xml:1179
#, no-c-format
msgid "This setting creates two new cache regions:"
msgstr ""

#. Tag: para
#: performance.xml:1181
#, no-c-format
msgid "<classname>org.hibernate.cache.StandardQueryCache, holding the cached query results"
msgstr ""

#. Tag: para
#: performance.xml:1186
#, no-c-format
msgid "<classname>org.hibernate.cache.UpdateTimestampsCache, holding timestamps of the most recent updates to queryable tables. These are used to validate the results as they are served from the query cache."
msgstr ""

#. Tag: para
#: performance.xml:1194
#, no-c-format
msgid "If you configure your underlying cache implementation to use expiry or timeouts is very important that the cache timeout of the underlying cache region for the UpdateTimestampsCache be set to a higher value than the timeouts of any of the query caches. In fact, we recommend that the the UpdateTimestampsCache region not be configured for expiry at all. Note, in particular, that an LRU cache expiry policy is never appropriate."
msgstr ""

#. Tag: para
#: performance.xml:1203
#, no-c-format
msgid "As mentioned above, most queries do not benefit from caching or their results. So by default, individual queries are not cached even after enabling query caching. To enable results caching for a particular query, call <literal>org.hibernate.Query.setCacheable(true). This call allows the query to look for existing cache results or add its results to the cache when it is executed."
msgstr ""

#. Tag: para
#: performance.xml:1211
#, no-c-format
msgid "The query cache does not cache the state of the actual entities in the cache; it caches only identifier values and results of value type. For this reaso, the query cache should always be used in conjunction with the second-level cache for those entities expected to be cached as part of a query result cache (just as with collection caching)."
msgstr ""

#. Tag: title
#: performance.xml:1221
#, no-c-format
msgid "Query cache regions"
msgstr ""

#. Tag: para
#: performance.xml:1223
#, no-c-format
msgid "If you require fine-grained control over query cache expiration policies, you can specify a named cache region for a particular query by calling <literal>Query.setCacheRegion()."
msgstr ""

#. Tag: programlisting
#: performance.xml:1227
#, no-c-format
msgid ""
      "List blogs = sess.createQuery(\"from Blog blog where blog.blogger = :blogger\")\n"
      "        .setEntity(\"blogger\", blogger)\n"
      "        .setMaxResults(15)\n"
      "        .setCacheable(true)\n"
      "        .setCacheRegion(\"frontpages\")\n"
      "        .list();"
msgstr ""

#. Tag: para
#: performance.xml:1229
#, no-c-format
msgid "If you want to force the query cache to refresh one of its regions (disregard any cached results it finds there) you can use <literal>org.hibernate.Query.setCacheMode(CacheMode.REFRESH). In conjunction with the region you have defined for the given query, Hibernate will selectively force the results cached in that particular region to be refreshed. This is particularly useful in cases where underlying data may have been updated via a separate process and is a far more efficient alternative to bulk eviction of the region via org.hibernate.SessionFactory.evictQueries()."
msgstr ""

#. Tag: title
#: performance.xml:1242
#, no-c-format
msgid "Understanding Collection performance"
msgstr ""

#. Tag: para
#: performance.xml:1244
#, no-c-format
msgid "In the previous sections we have covered collections and their applications. In this section we explore some more issues in relation to collections at runtime."
msgstr ""

#. Tag: title
#: performance.xml:1249
#, no-c-format
msgid "Taxonomy"
msgstr ""

#. Tag: para
#: performance.xml:1251
#, no-c-format
msgid "Hibernate defines three basic kinds of collections:"
msgstr ""

#. Tag: para
#: performance.xml:1255
#, no-c-format
msgid "collections of values"
msgstr ""

#. Tag: para
#: performance.xml:1259
#, no-c-format
msgid "one-to-many associations"
msgstr ""

#. Tag: para
#: performance.xml:1263
#, no-c-format
msgid "many-to-many associations"
msgstr ""

#. Tag: para
#: performance.xml:1267
#, no-c-format
msgid "This classification distinguishes the various table and foreign key relationships but does not tell us quite everything we need to know about the relational model. To fully understand the relational structure and performance characteristics, we must also consider the structure of the primary key that is used by Hibernate to update or delete collection rows. This suggests the following classification:"
msgstr ""

#. Tag: para
#: performance.xml:1276
#, no-c-format
msgid "indexed collections"
msgstr ""

#. Tag: para
#: performance.xml:1280
#, no-c-format
msgid "sets"
msgstr ""

#. Tag: para
#: performance.xml:1284
#, no-c-format
msgid "bags"
msgstr ""

#. Tag: para
#: performance.xml:1288
#, no-c-format
msgid "All indexed collections (maps, lists, and arrays) have a primary key consisting of the <literal><key> and <index> columns. In this case, collection updates are extremely efficient. The primary key can be efficiently indexed and a particular row can be efficiently located when Hibernate tries to update or delete it."
msgstr ""

#. Tag: para
#: performance.xml:1295
#, no-c-format
msgid "Sets have a primary key consisting of <literal><key> and element columns. This can be less efficient for some types of collection element, particularly composite elements or large text or binary fields, as the database may not be able to index a complex primary key as efficiently. However, for one-to-many or many-to-many associations, particularly in the case of synthetic identifiers, it is likely to be just as efficient. If you want SchemaExport to actually create the primary key of a <set>, you must declare all columns as not-null=\"true\"."
msgstr ""

#. Tag: para
#: performance.xml:1306
#, no-c-format
msgid "<literal><idbag> mappings define a surrogate key, so they are efficient to update. In fact, they are the best case."
msgstr ""

#. Tag: para
#: performance.xml:1309
#, no-c-format
msgid "Bags are the worst case since they permit duplicate element values and, as they have no index column, no primary key can be defined. Hibernate has no way of distinguishing between duplicate rows. Hibernate resolves this problem by completely removing in a single <literal>DELETE and recreating the collection whenever it changes. This can be inefficient."
msgstr ""

#. Tag: para
#: performance.xml:1316
#, no-c-format
msgid "For a one-to-many association, the \"primary key\" may not be the physical primary key of the database table. Even in this case, the above classification is still useful. It reflects how Hibernate \"locates\" individual rows of the collection."
msgstr ""

#. Tag: title
#: performance.xml:1323
#, no-c-format
msgid "Lists, maps, idbags and sets are the most efficient collections to update"
msgstr ""

#. Tag: para
#: performance.xml:1326
#, no-c-format
msgid "From the discussion above, it should be clear that indexed collections and sets allow the most efficient operation in terms of adding, removing and updating elements."
msgstr ""

#. Tag: para
#: performance.xml:1330
#, no-c-format
msgid "There is, arguably, one more advantage that indexed collections have over sets for many-to-many associations or collections of values. Because of the structure of a <literal>Set, Hibernate does not UPDATE a row when an element is \"changed\". Changes to a Set always work via INSERT and DELETE of individual rows. Once again, this consideration does not apply to one-to-many associations."
msgstr ""

#. Tag: para
#: performance.xml:1338
#, no-c-format
msgid "After observing that arrays cannot be lazy, you can conclude that lists, maps and idbags are the most performant (non-inverse) collection types, with sets not far behind. You can expect sets to be the most common kind of collection in Hibernate applications. This is because the \"set\" semantics are most natural in the relational model."
msgstr ""

#. Tag: para
#: performance.xml:1344
#, no-c-format
msgid "However, in well-designed Hibernate domain models, most collections are in fact one-to-many associations with <literal>inverse=\"true\". For these associations, the update is handled by the many-to-one end of the association, and so considerations of collection update performance simply do not apply."
msgstr ""

#. Tag: title
#: performance.xml:1352
#, no-c-format
msgid "Bags and lists are the most efficient inverse collections"
msgstr ""

#. Tag: para
#: performance.xml:1354
#, no-c-format
msgid "There is a particular case, however, in which bags, and also lists, are much more performant than sets. For a collection with <literal>inverse=\"true\", the standard bidirectional one-to-many relationship idiom, for example, we can add elements to a bag or list without needing to initialize (fetch) the bag elements. This is because, unlike a set, Collection.add() or Collection.addAll() must always return true for a bag or List. This can make the following common code much faster:"
msgstr ""

#. Tag: programlisting
#: performance.xml:1365
#, no-c-format
msgid ""
      "Parent p = (Parent) sess.load(Parent.class, id);\n"
      "Child c = new Child();\n"
      "c.setParent(p);\n"
      "p.getChildren().add(c);  //no need to fetch the collection!\n"
      "sess.flush();"
msgstr ""

#. Tag: title
#: performance.xml:1369
#, no-c-format
msgid "One shot delete"
msgstr ""

#. Tag: para
#: performance.xml:1371
#, no-c-format
msgid "Deleting collection elements one by one can sometimes be extremely inefficient. Hibernate knows not to do that in the case of an newly-empty collection (if you called <literal>list.clear(), for example). In this case, Hibernate will issue a single DELETE."
msgstr ""

#. Tag: para
#: performance.xml:1377
#, no-c-format
msgid "Suppose you added a single element to a collection of size twenty and then remove two elements. Hibernate will issue one <literal>INSERT statement and two DELETE statements, unless the collection is a bag. This is certainly desirable."
msgstr ""

#. Tag: para
#: performance.xml:1383
#, no-c-format
msgid "However, suppose that we remove eighteen elements, leaving two and then add thee new elements. There are two possible ways to proceed"
msgstr ""

#. Tag: para
#: performance.xml:1389
#, no-c-format
msgid "delete eighteen rows one by one and then insert three rows"
msgstr ""

#. Tag: para
#: performance.xml:1394
#, no-c-format
msgid "remove the whole collection in one SQL <literal>DELETE and insert all five current elements one by one"
msgstr ""

#. Tag: para
#: performance.xml:1400
#, no-c-format
msgid "Hibernate cannot know that the second option is probably quicker. It would probably be undesirable for Hibernate to be that intuitive as such behavior might confuse database triggers, etc."
msgstr ""

#. Tag: para
#: performance.xml:1404
#, no-c-format
msgid "Fortunately, you can force this behavior (i.e. the second strategy) at any time by discarding (i.e. dereferencing) the original collection and returning a newly instantiated collection with all the current elements."
msgstr ""

#. Tag: para
#: performance.xml:1409
#, no-c-format
msgid "One-shot-delete does not apply to collections mapped <literal>inverse=\"true\"."
msgstr ""

#. Tag: title
#: performance.xml:1415
#, no-c-format
msgid "Monitoring performance"
msgstr ""

#. Tag: para
#: performance.xml:1417
#, no-c-format
msgid "Optimization is not much use without monitoring and access to performance numbers. Hibernate provides a full range of figures about its internal operations. Statistics in Hibernate are available per <literal>SessionFactory."
msgstr ""

#. Tag: title
#: performance.xml:1423
#, no-c-format
msgid "Monitoring a SessionFactory"
msgstr ""

#. Tag: para
#: performance.xml:1425
#, no-c-format
msgid "You can access <literal>SessionFactory metrics in two ways. Your first option is to call sessionFactory.getStatistics() and read or display the Statistics yourself."
msgstr ""

#. Tag: para
#: performance.xml:1430
#, no-c-format
msgid "Hibernate can also use JMX to publish metrics if you enable the <literal>StatisticsService MBean. You can enable a single MBean for all your SessionFactory or one per factory. See the following code for minimalistic configuration examples:"
msgstr ""

#. Tag: programlisting
#: performance.xml:1435
#, no-c-format
msgid ""
      "// MBean service registration for a specific SessionFactory\n"
      "Hashtable tb = new Hashtable();\n"
      "tb.put(\"type\", \"statistics\");\n"
      "tb.put(\"sessionFactory\", \"myFinancialApp\");\n"
      "ObjectName on = new ObjectName(\"hibernate\", tb); // MBean object name\n"
      "\n"
      "StatisticsService stats = new StatisticsService(); // MBean implementation\n"
      "stats.setSessionFactory(sessionFactory); // Bind the stats to a SessionFactory\n"
      "server.registerMBean(stats, on); // Register the Mbean on the server"
msgstr ""

#. Tag: programlisting
#: performance.xml:1437
#, no-c-format
msgid ""
      "// MBean service registration for all SessionFactory's\n"
      "Hashtable tb = new Hashtable();\n"
      "tb.put(\"type\", \"statistics\");\n"
      "tb.put(\"sessionFactory\", \"all\");\n"
      "ObjectName on = new ObjectName(\"hibernate\", tb); // MBean object name\n"
      "\n"
      "StatisticsService stats = new StatisticsService(); // MBean implementation\n"
      "server.registerMBean(stats, on); // Register the MBean on the server"
msgstr ""

#. Tag: para
#: performance.xml:1439
#, no-c-format
msgid "You can activate and deactivate the monitoring for a <literal>SessionFactory:"
msgstr ""

#. Tag: para
#: performance.xml:1444
#, no-c-format
msgid "at configuration time, set <literal>hibernate.generate_statistics to false"
msgstr ""

#. Tag: para
#: performance.xml:1452
#, no-c-format
msgid "at runtime: <literal>sf.getStatistics().setStatisticsEnabled(true) or hibernateStatsBean.setStatisticsEnabled(true)"
msgstr ""

#. Tag: para
#: performance.xml:1458
#, no-c-format
msgid "Statistics can be reset programmatically using the <literal>clear() method. A summary can be sent to a logger (info level) using the logSummary() method."
msgstr ""

#. Tag: title
#: performance.xml:1464
#, no-c-format
msgid "Metrics"
msgstr ""

#. Tag: para
#: performance.xml:1466
#, no-c-format
msgid "Hibernate provides a number of metrics, from basic information to more specialized information that is only relevant in certain scenarios. All available counters are described in the <literal>Statistics interface API, in three categories:"
msgstr ""

#. Tag: para
#: performance.xml:1473
#, no-c-format
msgid "Metrics related to the general <literal>Session usage, such as number of open sessions, retrieved JDBC connections, etc."
msgstr ""

#. Tag: para
#: performance.xml:1479
#, no-c-format
msgid "Metrics related to the entities, collections, queries, and caches as a whole (aka global metrics)."
msgstr ""

#. Tag: para
#: performance.xml:1484
#, no-c-format
msgid "Detailed metrics related to a particular entity, collection, query or cache region."
msgstr ""

#. Tag: para
#: performance.xml:1489
#, no-c-format
msgid "For example, you can check the cache hit, miss, and put ratio of entities, collections and queries, and the average time a query needs. Be aware that the number of milliseconds is subject to approximation in Java. Hibernate is tied to the JVM precision and on some platforms this might only be accurate to 10 seconds."
msgstr ""

#. Tag: para
#: performance.xml:1495
#, no-c-format
msgid "Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection, cache region, etc.). You can access the metrics of a particular entity, collection or cache region through its name, and through its HQL or SQL representation for queries. Please refer to the <literal>Statistics, EntityStatistics, CollectionStatistics, SecondLevelCacheStatistics, and QueryStatistics API Javadoc for more information. The following code is a simple example:"
msgstr ""

#. Tag: programlisting
#: performance.xml:1506
#, no-c-format
msgid ""
      "Statistics stats = HibernateUtil.sessionFactory.getStatistics();\n"
      "\n"
      "double queryCacheHitCount  = stats.getQueryCacheHitCount();\n"
      "double queryCacheMissCount = stats.getQueryCacheMissCount();\n"
      "double queryCacheHitRatio =\n"
      "  queryCacheHitCount / (queryCacheHitCount + queryCacheMissCount);\n"
      "\n"
      "log.info(\"Query Hit ratio:\" + queryCacheHitRatio);\n"
      "\n"
      "EntityStatistics entityStats =\n"
      "  stats.getEntityStatistics( Cat.class.getName() );\n"
      "long changes =\n"
      "        entityStats.getInsertCount()\n"
      "        + entityStats.getUpdateCount()\n"
      "        + entityStats.getDeleteCount();\n"
      "log.info(Cat.class.getName() + \" changed \" + changes + \"times\"  );"
msgstr ""

#. Tag: para
#: performance.xml:1508
#, no-c-format
msgid "You can work on all entities, collections, queries and region caches, by retrieving the list of names of entities, collections, queries and region caches using the following methods: <literal>getQueries(), getEntityNames(), getCollectionRoleNames(), and getSecondLevelCacheRegionNames()."
msgstr ""

Other Hibernate examples (source code examples)

Here is a short list of links related to this Hibernate performance.pot source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.