Cache Named Queries with Hibernate

In the last post (see organize your named queries) a nice way to organize named queries has been proposed. The advantages of using named queries in the first place is discussed in the mentioned post, too. Hibernate offers a nice way removing a big disadvantage of named queries or to be more precise of JPQL queries in general, as compared with associations of an entity. Query results are not cached by default, neither in the first level nor in the second level cache. But you may add a query hint in order to advise hibernate to cache the results. Fortunately, like for associations, the query cache does store the ids for resulting entities, so the first and second level cache is requested for the respective objects. If the values are not present in the cache they are retrieved from the underlying resource.
Read More

Organize Your Named JPQL Queries

Named queries have some nice properties. They are precompiled and therefore faster than their “normal” counterparts, encourage to use named parameters, make your code easier to read and avoid messing up your code with string concatenated queries. A nice addon is, that named queries are validated during the creation of the persistence unit. If you have a unit test (see unit test db schema and named queries), checking whether the entities represent a valid DB Schema, the named queries are validated, too. So, there will be syntactical as well as some static analysis (e.g. “exist all referenced entities?”) during the test phase, before your application is even packaged.
Read More

EAGER Fetch of Multiple Associations

Associations are fetched lazily by default. You may change this behavior by setting the parameter fetch=FetchType.EAGER of the annotation @OneToMany for example. This has the disadvantage, that the association is eagerly fetched each time the respective entity is retrieved from the underlying database. This leads to the so called cartesian product read issue since the respective association is retrieved with the query of the owning entity via LEFT OUTER JOIN (see JPQL and joins). So, a lot of redundant data might be retrieved from the database, since the OR-Mapper has no interception point where he can prevent to retrieve data cached already. Another way is to overwrite the lazy fetch type in a jpql query (see override fetch type). So the cartesian product read issue does still exist, but you can control when to eagerly fetch an assoctiation and when not.
Read More

Ordering Collections with JPA

Often there is the need to sort an entity or a collection, e.g. If you have a list of line items in a bill and do not want that the order may change or is semantically wrong. Unfortunately, using a java.util.List will not suffice, since the DB has not to retain the order of the list. You might recognize this only after a long time, since some RDBMS will return the rows by insertion order. There are different ways to introduce an ordering with JPA (see Java Persistence: Ordering).
Read More

Override fetch type in JPQL Queries

Executing a getter — representing a one-to-many or many-to-many association — on an entity causes one or n (with n entries in the collection) database calls, depending on the fetching strategy (see fetch strategies). This is a nasty little detail that may cause performance bottlenecks. Changing the fetch type (lazy/eager) may not be appropriate, since an association is generally used in more than one context, so there may be contradictory concerns. Generally spoken, an eager fetching is only in rare occasions a good idea on one-to-many or many-to-many associations, since this leads to the cartesian product problem (simply put, you have to read [nearly] the hole db in order to get one entity). Fortunately there is another solution that enables overriding a lazy fetch type in a dedicated JPQL-Query. This may entail a hole bunch of JPQL queries you will have to write (not more queries to execute on the db!!!), since you want to eagerly fetch an association in one situation but not in another.
Read More

OR-Mapper and the ‘many queries’ problem

Applications using an OR-Mapper like Hibernate or OpenJPA are reckoned as to be slow. This observation is true, since there is an overhead compared to using hand-crafted and optimized SQL-Queries and Database structure. But the overhead has not to be as big as it is often observed in applications with entities. There is a lot of potential optimizing such a system. Unfortunately you won’t be able to circumvent quarelling with the underlying database, although a persistence layer is all about abstraction. Not bringing into mind what happens in your persistence layer will lead to really bad performance. Read More

Unnecessary Code Detector

Recently I found a nice eclipse plugin for finding dead code. The standard eclipse check finds unused private fields and methods, only. You may use STRG+SHIFT+G for finding references to a public class or method in advance. But this approach is limited to search for methods/classes without references one by one, which is very time consuming. The UCDetector starts a search for methods and classses without any references to it in all projects in the current workspace respecting inheritance and presents the results in the ‘Problems’ view. Read More

Fetch strategy subselect for hibernate

The standard fetch strategy for collections in hibernate is lazy select fetching (hibernate performance). So if you retrieve some entities (for example via a query or a collection association) with a lazy collection association, subsequent calls to this lazy association will be retrieved one by one in further requests, for example. This is called the N+1-query problem, since there is one query for retrieving the entities itself and N additional queries for the lazy association. You can reduce the overhead by setting the hibernate.default_batch_fetch_size for your persistence unit in the persistence.xml. This reduces the problem to an N/batch_size +1-query problem. You can tell hibernate to use only 1+1-queries, if you set the fetch strategy to subselect fetching. This way, all entities in the association collections of the entities are retrieved in one query as soon as one of the associations is accessed. This will be helpfull only, if you do not pick one of the objects and retrieve the association, but iterate through your results and access the association of each of them. It is even contra productive otherwise. Read More

Interface with self-referencing generic type

The Comparable interface has a generic type parameter, which is used for self-referencing in subclasses (I don’t know any other use for it) :

public interface Comparable<E> {
  public int compareTo(E other);
}

public class ComparableInteger implements Comparable<ComparableInteger> {
  private int val;
  public void compareTo(ComparableInteger other) {
    return val > other ? 1 : (val == other ? 0 : -1);
}

But what if you need to access methods of the interface on the generic type parameter? Then you can do a recursive declaration of the type parameter. Read More