Lazy query container

When to Use Lazy Query Container?

Typical usage scenario is browsing a large persistent data set in Vaadin Table. LQC minimizes the complexity of the required custom implementation while retaining all table features like sorting and lazy loading. LQC delegates sorting of the data set to the backend data store instead of sorting in memory. Sorting in memory would require entire data set to be loaded to application server.

What is Lazy Loading?

In this context lazy loading refers to loading items to table on demand in batches instead of loading the entire data set to memory at once. This is useful in most business applications as row counts often range from thousands to millions. Loading more than few hundred rows to memory often causes considerable delay in page response.

Getting Started

To use LQC you need to get the add-on from add-ons page and drop it to your projects WEB-INF/lib directory. After this you can use existing query factory (JpaQueryFactory), extend AbstractBeanQuery or proceed to implement custom Query and QueryFactory. Finally you need to instantiate LazyQueryContainer and give your query factory as constructor parameter.

How to Use Lazy Query Container with Table?

LQC is implementation of Vaadin Container interface. Please refer to Book of Vaadin for usage details of Table and Container implementations generally.

How to Use EntityContainer

EntityContainer is specialized version LazyQueryContainer allowing easy use of JPA as persistence layer and supports defining where criteria and corresponding parameter map in addition to normal LazyQueryContainer features:

Java

  1. entityContainer = new EntityContainer<Task>(entityManager, true, Task.class, 100,
  2. new Object[] { "name" }, new boolean[] { true });
  3. entityContainer.addContainerProperty("name", String.class, "", true, true);
  4. entityContainer.addContainerProperty("reporter", String.class, "", true, true);
  5. entityContainer.addContainerProperty("assignee", String.class, "", true, true);
  6. whereParameters = new HashMap<String, Object>();
  7. whereParameters.put("name", nameFilter);
  8. entityContainer.filter("e.name=:name", whereParameters);
  9. table.setContainerDataSource(entityContainer);

How to Use BeanQueryFactory

BeanQueryFactory and AbstractBeanQuery are used to implement queries saving and loading JavaBeans.

The BeanQueryFactory is used as follows with the Vaadin table. Usage of queryConfiguration is optional and enables passing objects to the constructed queries:

Java

  1. Table table = new Table();
  2. BeanQueryFactory<TaskBeanQuery> queryFactory = new
  3. BeanQueryFactory<TaskBeanQuery>(TaskBeanQuery.class);
  4. Map<String,Object> queryConfiguration = new HashMap<String,Object>();
  5. queryConfiguration.put("taskService",new TaskService());
  6. queryFactory.setQueryConfiguration(queryConfiguration);
  7. LazyQueryContainer container = new LazyQueryContainer(queryFactory,50);
  8. table.setContainerDataSource(container);

Here is a simple example of AbstractBeanQuery implementation:

Java

  1. public class TaskBeanQuery extends AbstractBeanQuery<Task> {
  2. public TaskBeanQuery(QueryDefinition definition,
  3. Map<String, Object> queryConfiguration, Object[] sortPropertyIds,
  4. boolean[] sortStates) {
  5. super(definition, queryConfiguration, sortPropertyIds, sortStates);
  6. }
  7. @Override
  8. protected Task constructBean() {
  9. return new Task();
  10. }
  11. @Override
  12. public int size() {
  13. TaskService taskService =
  14. (TaskService)queryConfiguration.get("taskService");
  15. return taskService.countTasks();
  16. }
  17. @Override
  18. protected List<Task> loadBeans(int startIndex, int count) {
  19. TaskService taskService =
  20. (TaskService)queryConfiguration.get("taskService");
  21. return taskService.loadTasks(startIndex, count, sortPropertyIds, sortStates);
  22. }
  23. @Override
  24. protected void saveBeans(List<Task> addedTasks, List<Task> modifiedTasks,
  25. List<Task> removedTasks) {
  26. TaskService taskService =
  27. (TaskService)queryConfiguration.get("taskService");
  28. taskService.saveTasks(addedTasks, modifiedTasks, removedTasks);
  29. }
  30. }

How to Implement Custom Query and QueryFactory?

QueryFactory instantiates new query whenever sort state changes or refresh is requested. Query can construct for example named JPA query in constructor. Data loading starts by invocation of Query.size() method and after this data is loaded in batches by invocations of Query.loadItems().

Please remember that the idea is to load data in batches. You do not need to load the entire data set to memory. If you do that you are better of with some other container implementation like BeanItemContainer. To be able to load database in batches you need your storage to provide you with the result set size and ability to load rows in batches as illustrated by the following pseudo code:

Java

  1. int countObjects(SearchCriteria searchCriteria);
  2. List<Object> getObjects(SearchCriteria searchCriteria, int startIndex, int batchSize);

Here is simple read only JPA example to illustrate the idea. You can find further examples from add-on page.

Java

  1. package com.logica.portlet.example;
  2. import javax.persistence.EntityManager;
  3. import org.vaadin.addons.lazyquerycontainer.Query;
  4. import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
  5. import org.vaadin.addons.lazyquerycontainer.QueryFactory;
  6. public class MovieQueryFactory implements QueryFactory {
  7. private EntityManager entityManager;
  8. private QueryDefinition definition;
  9. public MovieQueryFactory(EntityManager entityManager) {
  10. super();
  11. this.entityManager = entityManager;
  12. }
  13. @Override
  14. public void setQueryDefinition(QueryDefinition definition) {
  15. this.definition = definition;
  16. }
  17. @Override
  18. public Query constructQuery(Object[] sortPropertyIds, boolean[] sortStates) {
  19. return new MovieQuery(entityManager,definition,sortPropertyIds,sortStates);
  20. }
  21. }

Java

  1. package com.logica.portlet.example;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.persistence.EntityManager;
  5. import org.vaadin.addons.lazyquerycontainer.Query;
  6. import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
  7. import com.logica.example.jpa.Movie;
  8. import com.vaadin.data.Item;
  9. import com.vaadin.data.util.BeanItem;
  10. public class MovieQuery implements Query {
  11. private EntityManager entityManager;
  12. private QueryDefinition definition;
  13. private String criteria = "";
  14. public MovieQuery(EntityManager entityManager,
  15. QueryDefinition definition,
  16. Object[] sortPropertyIds,
  17. boolean[] sortStates) {
  18. super();
  19. this.entityManager = entityManager;
  20. this.definition = definition;
  21. for(int i=0;i<sortPropertyIds.length;i++) {
  22. if(i==0) {
  23. criteria = " ORDER BY";
  24. } else {
  25. criteria+ = ",";
  26. }
  27. criteria += " m." + sortPropertyIds[i];
  28. if(sortStates[i]) {
  29. criteria += " ASC";
  30. }
  31. else {
  32. criteria += " DESC";
  33. }
  34. }
  35. }
  36. @Override
  37. public Item constructItem() {
  38. return new BeanItem<Movie>(new Movie());
  39. }
  40. @Override
  41. public int size() {
  42. javax.persistence.Query query = entityManager.
  43. createQuery("SELECT count(m) from Movie as m");
  44. return (int)((Long) query.getSingleResult()).longValue();
  45. }
  46. @Override
  47. public List<Item> loadItems(int startIndex, int count) {
  48. javax.persistence.Query query = entityManager.
  49. createQuery("SELECT m from Movie as m" + criteria);
  50. query.setFirstResult(startIndex);
  51. query.setMaxResults(count);
  52. List<Movie> movies=query.getResultList();
  53. List<Item> items=new ArrayList<Item>();
  54. for(Movie movie : movies) {
  55. items.add(new BeanItem<Movie>(movie));
  56. }
  57. return items;
  58. }
  59. @Override
  60. public void saveItems(List<Item> addedItems, List<Item> modifiedItems,
  61. List<Item> removedItems) {
  62. throw new UnsupportedOperationException();
  63. }
  64. @Override
  65. public boolean deleteAllItems() {
  66. throw new UnsupportedOperationException();
  67. }
  68. }

How to Implement Editable Table?

First you need to implement the Query.saveItems() method. After this you need to set some of the properties editable in your items and set table in editable mode as well. After user has made changes you need to call container.commit() or container.discard() to commit or rollback respectively. Please find complete examples of table handing and editable JPA query from add-on page.

How to Use Debug Properties?

LQC provides set of debug properties which give information about response times, number of queries constructed and data batches loaded. To use these properties the items used need to contain these properties with correct ids and types. If you use dynamic items you can defined them in the query definition and add them on demand in the query implementation.

Java

  1. container.addContainerProperty(LazyQueryView.DEBUG_PROPERTY_ID_QUERY_INDEX, Integer.class, 0, true, false);
  2. container.addContainerProperty(LazyQueryView.DEBUG_PROPERTY_ID_BATCH_INDEX, Integer.class, 0, true, false);
  3. container.addContainerProperty(LazyQueryView.DEBUG_PROPERTY_ID_BATCH_QUERY_TIME, Integer.class, 0, true, false);

How to Use Row Status Indicator Column in Table?

When creating editable tables LCQ provides QueryItemStatusColumnGenerator which can be used to generate the status column cells to the table. In addition you need to have the status property in your items. If your items respect the query definition you can implement this as follows:

Java

  1. container.addContainerProperty(LazyQueryView.PROPERTY_ID_ITEM_STATUS,
  2. QueryItemStatus.class, QueryItemStatus.None, true, false);

How to Use Status Column and Debug Columns with Beans

Here is example query implementation which shows how JPA and beans can be used together with status and debug properties:

Java

  1. package org.vaadin.addons.lazyquerycontainer.example;
  2. import java.beans.BeanInfo;
  3. import java.beans.Introspector;
  4. import java.beans.PropertyDescriptor;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import javax.persistence.EntityManager;
  8. import org.vaadin.addons.lazyquerycontainer.CompositeItem;
  9. import org.vaadin.addons.lazyquerycontainer.Query;
  10. import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
  11. import com.vaadin.data.Item;
  12. import com.vaadin.data.util.BeanItem;
  13. import com.vaadin.data.util.ObjectProperty;
  14. public class TaskQuery implements Query {
  15. private EntityManager entityManager;
  16. private QueryDefinition definition;
  17. private String criteria=" ORDER BY t.name ASC";
  18. public TaskQuery(EntityManager entityManager, QueryDefinition definition,
  19. Object[] sortPropertyIds, boolean[] sortStates) {
  20. super();
  21. this.entityManager = entityManager;
  22. this.definition = definition;
  23. for(int i=0; i<sortPropertyIds.length; i++) {
  24. if(i==0) {
  25. criteria = " ORDER BY";
  26. } else {
  27. criteria+ = ",";
  28. }
  29. criteria += " t." + sortPropertyIds[i];
  30. if(sortStates[i]) {
  31. criteria += " ASC";
  32. }
  33. else {
  34. criteria += " DESC";
  35. }
  36. }
  37. }
  38. @Override
  39. public Item constructItem() {
  40. Task task=new Task();
  41. try {
  42. BeanInfo info = Introspector.getBeanInfo( Task.class );
  43. for ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {
  44. for(Object propertyId : definition.getPropertyIds()) {
  45. if(pd.getName().equals(propertyId)) {
  46. pd.getWriteMethod().invoke(task,
  47. definition.getPropertyDefaultValue(propertyId));
  48. }
  49. }
  50. }
  51. } catch(Exception e) {
  52. throw new RuntimeException("Error in bean property population");
  53. }
  54. return toItem(task);
  55. }
  56. @Override
  57. public int size() {
  58. javax.persistence.Query query = entityManager.createQuery(
  59. "SELECT count(t) from Task as t");
  60. return (int)((Long) query.getSingleResult()).longValue();
  61. }
  62. @Override
  63. public List<Item> loadItems(int startIndex, int count) {
  64. javax.persistence.Query query = entityManager.createQuery(
  65. "SELECT t from Task as t" + criteria);
  66. query.setFirstResult(startIndex);
  67. query.setMaxResults(count);
  68. List<Task> tasks=query.getResultList();
  69. List<Item> items=new ArrayList<Item>();
  70. for(Task task : tasks) {
  71. items.add(toItem(task));
  72. }
  73. return items;
  74. }
  75. @Override
  76. public void saveItems(List<Item> addedItems, List<Item> modifiedItems,
  77. List<Item> removedItems) {
  78. entityManager.getTransaction().begin();
  79. for(Item item : addedItems) {
  80. entityManager.persist(fromItem(item));
  81. }
  82. for(Item item : modifiedItems) {
  83. entityManager.persist(fromItem(item));
  84. }
  85. for(Item item : removedItems) {
  86. entityManager.remove(fromItem(item));
  87. }
  88. entityManager.getTransaction().commit();
  89. }
  90. @Override
  91. public boolean deleteAllItems() {
  92. throw new UnsupportedOperationException();
  93. }
  94. private Item toItem(Task task) {
  95. BeanItem<Task> beanItem= new BeanItem<Task>(task);
  96. CompositeItem compositeItem=new CompositeItem();
  97. compositeItem.addItem("task", beanItem);
  98. for(Object propertyId : definition.getPropertyIds()) {
  99. if(compositeItem.getItemProperty(propertyId)==null) {
  100. compositeItem.addItemProperty(propertyId, new ObjectProperty(
  101. definition.getPropertyDefaultValue(propertyId),
  102. definition.getPropertyType(propertyId),
  103. definition.isPropertyReadOnly(propertyId)));
  104. }
  105. }
  106. return compositeItem;
  107. }
  108. private Task fromItem(Item item) {
  109. return (Task)((BeanItem)(((CompositeItem)item).getItem("task"))).getBean();
  110. }
  111. }