JPA 2.0 Criteria Lazy Container

Starting a new thread to discuss the
JPA 2.0 Criteria Lazy Container
add-on, which is now approaching release candidate maturity.

Briefly, this add-on allows building a database container without writing any SQL, in a type-safe fashion, using the standard Java JPA 2.0 Criteria API. Arbitrary queries and groupings are supported and whatever columns returned by the query are automatically present in the container. It is also possible to perform arbitrary joins and use any property from any of the joined entites in the container. The container builds upon the well-known LazyQueryContainer.

== Release 0.4.6 ==

  • CriteriaContainer now supports nested retrieval
    The items of the container will then retrieve the value of assignee.getClass() when
    accessing the “assignee.class” property.
    Any string that can be understood by Jakarta PropertyUtils.getProperty can be
    used (e.g. person.address.zipcode or even person.children[0]
    However, there must be an accessor (getX() or isX()) for this to work.

== Release 0.4.5 ==

  • setKeyPropertyId() can be used to state that the container should return a key
    from the underlying data source instead of the index in the container. For example
    taskContainer.setKeyPropertyId(“taskId”) would return the taskId column. This is
    normally used when using the container with a Select, where it is useful to store
    a foreign key. NOTE: the Vaadin 6.5 implementation of Select performs a getItemIds()
    call, and is NOT lazy. This means that Select cannot be used for large data sets.
    If selecting from a large dataset, you probably need to use a Table, which does NOT
    attempt to get all the itemIds at once.

Hi Jean-François.

First of all congratulations on a very nice add-on.
Tested it for the last fiew days and I’m very pleased.

I’ve been experiencing some “detached entity passed to persist” errors while updating an entity and I’ve traced the problem to the saveItems method of the CriteriaItemHelper class.

Now this probably has to do with something that I did earlier but still I was wondering why you used :

for (Item item : modifiedItems) {

Instead of:

for (Item item : modifiedItems) {

The merge seams to do the trick for me but like I mentioned I’m probably doing something wrong earlier in the process.

Best Regards

Gonçalo Trindade

Oddly enough, the code was actually copied directly from the LazyQueryContainer routine it overrides, and I remember that someone had made the same comment to the original author. But since the code remained as is, and the semantics of merge() and persist() are sometimes extremely subtle, I never challenged the code. I will look at this in more detail tomorrow, prior to pushing a small bug fix I just did.

Thank you for your kind words.

Thank you for the prompt response.

As you suggested, I took a peek at LazyContainer’s EntityQuery class and the saveItems method looks like this:

  public void saveItems(final List<Item> addedItems, final List<Item> modifiedItems, final List<Item> removedItems) {
        if (applicationTransactionManagement) {
        try {
            for (Item item : addedItems) {
                if (!removedItems.contains(item)) {
            for (Item item : modifiedItems) {
                if (!removedItems.contains(item)) {
                    Object entity = fromItem(item);
                    if (queryDefinition.isDetachedEntities()) {
                        entity = entityManager.merge(entity);
            for (Item item : removedItems) {
                if (!addedItems.contains(item)) {
                    Object entity = fromItem(item);
                    if (queryDefinition.isDetachedEntities()) {
                        entity = entityManager.merge(entity);
            if (applicationTransactionManagement) {
        } catch (Exception e) {
            if (applicationTransactionManagement) {
                if (entityManager.getTransaction().isActive()) {
            throw new RuntimeException(e);            

So i’ve reproduced this in the CriteriaItemHelper class and added “private boolean detachedEntities;” to the AbstractCriteriaQueryDefinition in order to control if detached entites are used at the container’s creation (just like in LazyQueryContainer).

This works for me.

Best Regards

Gonçalo Trindade

== Release 0.5.0 ==
  * Added support for isDetachedEntities() as in LazyQueryContainer 1.2.8. If this parameter
    is set, the entities loaded are immediately detached, and a merge() is performed on
    update and remove.  Added corresponding constructors to BeanTupleQueryDefinition,
    CriteriaQueryDefinition and CriteriaContainer.
  * Improved caching of query size to avoid unnecessary calls to select count()
  * Improved defensive programming if asking to load empty or negative count of items.
  * Improved runtime error message if a CriteriaQueryDefinition is used on a BeanTupleContainer,
    since the conventions for property names are different and this can lead to hard to diagnose

This should fix the issue reported by Gonçalo Trindade (thanks!). The improvement was made to both BeanTupleContainer and CriteriaContainer.

Also, an example has been added for a situation when you want to join two entities on a field, but do not want to declare a relationship to JPA (you don’t want to worry about fetching the linked entities, or this is an ad hoc query).

Hi Jean!

Im in troubles with Nested Properties.

If a nested property is null, it’s causing a null pointer exception, that I belive might be avoided by container. For example:

Person → Login Account → username.

Not every person needs to have a login account. It permits null on relationship.

On the Table, I wanna show the username, in the case that Person haves a Username, otherwise, shows the default value of property.

In this case, the, using addContainerProperty(loginAccount.username) causes a null pointer exception on the container.

And another little thing: Will be possible to order the table based on nested properties? For now, I can only order by directly properties.

Im using the 0.50 version, and CriteriaContainer class.

Many thanks by atention!

I just realized that a few persons had posted issues and enhancement requests to the Googlecode home for the project. Unfortunately I was not being warned on updates, something I have now fixed.

The issues were fortunately quite easy to fix and an update should be coming shortly.

The enhancements relate to filtering, something I am currently looking at in the context of Vaadin 6.6 and a current project also, so this may well work out in the coming weeks as well.

There is now an EclipseLink branch in the source tree on GoogleCode ( for early adopters. The checkout is a set of Eclipse projects with full Maven pom.xml, so it should build right away if you have m2eclipse installed. See the release notes under the doc directory for EclipseLink limitations - basically, EclipseLink generates very peculiar non-working SQL with multiiple Criteria Roots so you have to stick with joins (which is what most people do anyway).

I am currently working on implementing the new Filterable interface and will likely wait until that is stable to issue a real 1.0 release.

Support for the Filterable interface is now on the default branch in the source tree, for courageous souls. Vaadin filters are translated to JPA 2.0 Criteria API and processed as such. I’ve implemented all the filters present in 6.6 and 6.7; commented out the 6.7 specifics for the time being.

See the project criteriaapp_test for a couple simple example (BeanTupleContainerFilteringApplication and EntityContainerFilteringApplication).


I have tried the EntityContainerFilteringApplication and a NullPointerException is killing me!
I’ve already tried ecliselink 2.3.0…2.4.0.

Thanks in advance!

at org.eclipse.persistence.internal.jpa.querydef.CriteriaQueryImpl.createCompoundQuery(
at org.eclipse.persistence.internal.jpa.querydef.CriteriaQueryImpl.translate(
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(
at org.vaadin.addons.beantuplecontainer.BeanTupleQueryDefinition.getSelectQuery(
at org.vaadin.addons.beantuplecontainer.BeanTupleItemHelper.(
at org.vaadin.addons.criteriacontainer.CriteriaItemHelper.(
at org.vaadin.addons.criteriacontainer.CriteriaQueryFactory.constructQuery(
at org.vaadin.addons.lazyquerycontainer.LazyQueryView.getQuery(
at org.vaadin.addons.lazyquerycontainer.LazyQueryView.size(
at org.vaadin.addons.beantuplecontainer.BeanTupleQueryView.init(
at org.vaadin.addons.beantuplecontainer.BeanTupleQueryView.size(
at org.vaadin.addons.lazyquerycontainer.LazyQueryContainer.size(
at org.vaadin.addons.beantuplecontainer.BeanTupleContainer.size(
at org.vaadin.addons.criteriacontainersample.AbstractEntityApplication.init(
at com.vaadin.Application.start(
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.startApplication(
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.service(
at javax.servlet.http.HttpServlet.service(
at org.apache.catalina.core.StandardWrapper.service(
at org.apache.catalina.core.StandardWrapperValve.invoke(
at org.apache.catalina.core.StandardContextValve.invoke(
at org.apache.catalina.core.StandardPipeline.doInvoke(
at org.apache.catalina.core.StandardPipeline.invoke(
at com.sun.enterprise.web.WebPipeline.invoke(
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(
at org.apache.catalina.core.StandardHostValve.invoke(
at org.apache.catalina.connector.CoyoteAdapter.doService(
at org.apache.catalina.connector.CoyoteAdapter.service(
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(
at com.sun.grizzly.http.ProcessorTask.doProcess(
at com.sun.grizzly.http.ProcessorTask.process(
at com.sun.grizzly.http.DefaultProtocolFilter.execute(
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(
at com.sun.grizzly.DefaultProtocolChain.execute(
at com.sun.grizzly.DefaultProtocolChain.execute(
at com.sun.grizzly.http.HttpProtocolChain.execute(
at com.sun.grizzly.ProtocolChainContextTask.doCall(
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(
at com.sun.grizzly.util.AbstractThreadPool$

You need to use 2.4.0-SNAPSHOT (or 2.3.1-SNAPSHOT). EclipseLink fixed the bug on August 17 2011.
(the actual version numbers I tested with are listed in the pom.xml file. Even if you don’t use Maven, getting familiar enough with the “dependencies” section of the pom can be worthwhile).

Hello Jean-Francois

I’ve been testing your Criteria Lazy Continer for a bit. Thanks very much for all your excellent work. It appears to hold considerable promise for our application. I’ve been having some issues with detached entities.

This is the code sequence that is generating the problem:



The resulting error message is:

SEVERE: Terminal error:
Cause: java.lang.RuntimeException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:
at com.vaadin.event.ListenerMethod.receiveEvent(
at com.vaadin.event.EventRouter.fireEvent(
at com.vaadin.ui.AbstractComponent.fireEvent(
at com.vaadin.ui.Button.fireClick(
at com.vaadin.ui.Button.changeVariables(
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleVariableBurst(
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleVariables(
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.doHandleUidlRequest(
at com.vaadin.terminal.gwt.server.CommunicationManager.handleUidlRequest(
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.service(
at javax.servlet.http.HttpServlet.service(
at org.mortbay.jetty.servlet.ServletHolder.handle(
at org.mortbay.jetty.servlet.ServletHandler.handle(
at org.mortbay.jetty.servlet.SessionHandler.handle(
at org.mortbay.jetty.handler.ContextHandler.handle(
at org.mortbay.jetty.webapp.WebAppContext.handle(
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(
at org.mortbay.jetty.handler.HandlerCollection.handle(
at org.mortbay.jetty.handler.HandlerWrapper.handle(
at org.mortbay.jetty.Server.handle(
at org.mortbay.jetty.HttpConnection.handleRequest(
at org.mortbay.jetty.HttpConnection$RequestHandler.content(
at org.mortbay.jetty.HttpParser.parseNext(
at org.mortbay.jetty.HttpParser.parseAvailable(
at org.mortbay.jetty.HttpConnection.handle(
at org.mortbay.thread.QueuedThreadPool$
Caused by: java.lang.RuntimeException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:
at org.vaadin.addons.criteriacontainer.CriteriaItemHelper.saveItems(
at org.vaadin.addons.lazyquerycontainer.LazyQueryView.commit(
at org.vaadin.addons.beantuplecontainer.BeanTupleQueryView.commit(
at org.vaadin.addons.lazyquerycontainer.LazyQueryContainer.commit(
at org.vaadin.addons.beantuplecontainer.BeanTupleContainer.commit(
at helpwaredb.dbdeb1.TwsPatientAdmin.buttonClick(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(
at com.vaadin.event.ListenerMethod.receiveEvent(
… 27 more
Caused by: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(
at org.vaadin.addons.criteriacontainer.CriteriaItemHelper.saveItems(
… 37 more
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist:
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(
at org.hibernate.impl.SessionImpl.firePersist(
at org.hibernate.impl.SessionImpl.persist(
at org.hibernate.impl.SessionImpl.persist(
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(
… 38 more

I would greatly appreciate your assistance in tracking this down. I’ve created a few different test modules. In some cases this seems to work fine, but in other cases it does not.

Thanks in advance for your aid.


Unless you explicitly use the “use detached entities” mode, the container does not detach entities. If you use that mode, the container will detach its entities on fetching, and remerge everything. I must confess not using that mode myself, it is there for compatibility with LazyQueryContainer.

If you create a container using an entity manager that is later closed, you cannot reuse that container, you need to create another one. So typically you end up with two kinds of containers – session (i.e. vaadin application) containers for things that persist from page to page, and request-level containers that get rebuilt on every invocation.

From the trace, it looks like you are editing an object; if it has been fetched from a table displayed on a previous http request, and you are editing it (on a new page), and your entity manager is allocated on each page, you may well be running into this problem.

When a (business) transaction straddles several HTTP requests, and can be performed in isolation of whatever else is happening in the database, you can allocate an entity manager for that business transactiion in that user’s application, and null it at the end. But you have to be aware that the entity manager is an object cache, and that you will need to deal with locking exceptions when you persist if you use optimistic locking. Just be aware that if you need to check a constraint on an object, you will need to refresh() it explicitly, or use another entity manager to look up the values you want “live”.

Thank you very much for your quick and thorough response. Your explanation is very helpful and much appreciated. It will be useful as I move forward with development.

For the record, it turns out that this specific issue resulted from incorrectly specifying a setter in the ENTITY definition class. It appears to be important to get those getters and setters right! Imagine that?

I was also having a similar problem in another class and that problem resulted from attempting to use an entity manager that had previously been closed.

Issue resolved, thanks to your help!