You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LazyQueryContainer.asciidoc 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. ---
  2. title: Lazy Query Container
  3. order: 2
  4. layout: page
  5. ---
  6. [[lazy-query-container]]
  7. = Lazy query container
  8. [[when-to-use-lazy-query-container]]
  9. When to Use Lazy Query Container?
  10. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  11. Typical usage scenario is browsing a large persistent data set in Vaadin
  12. Table. LQC minimizes the complexity of the required custom
  13. implementation while retaining all table features like sorting and lazy
  14. loading. LQC delegates sorting of the data set to the backend data store
  15. instead of sorting in memory. Sorting in memory would require entire
  16. data set to be loaded to application server.
  17. [[what-is-lazy-loading]]
  18. What is Lazy Loading?
  19. ~~~~~~~~~~~~~~~~~~~~~
  20. In this context lazy loading refers to loading items to table on demand
  21. in batches instead of loading the entire data set to memory at once.
  22. This is useful in most business applications as row counts often range
  23. from thousands to millions. Loading more than few hundred rows to memory
  24. often causes considerable delay in page response.
  25. [[getting-started]]
  26. Getting Started
  27. ~~~~~~~~~~~~~~~
  28. To use LQC you need to get the add-on from add-ons page and drop it to
  29. your projects WEB-INF/lib directory. After this you can use existing
  30. query factory (`JpaQueryFactory`), extend `AbstractBeanQuery` or proceed to
  31. implement custom `Query` and `QueryFactory`. Finally you need to instantiate
  32. `LazyQueryContainer` and give your query factory as constructor parameter.
  33. [[how-to-use-lazy-query-container-with-table]]
  34. How to Use Lazy Query Container with Table?
  35. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  36. LQC is implementation of Vaadin Container interface. Please refer to
  37. Book of Vaadin for usage details of Table and Container implementations
  38. generally.
  39. [[how-to-use-entitycontainer]]
  40. How to Use EntityContainer
  41. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  42. `EntityContainer` is specialized version `LazyQueryContainer` allowing easy
  43. use of JPA as persistence layer and supports defining where criteria and
  44. corresponding parameter map in addition to normal `LazyQueryContainer`
  45. features:
  46. [source,java]
  47. ....
  48. entityContainer = new EntityContainer<Task>(entityManager, true, Task.class, 100,
  49. new Object[] { "name" }, new boolean[] { true });
  50. entityContainer.addContainerProperty("name", String.class, "", true, true);
  51. entityContainer.addContainerProperty("reporter", String.class, "", true, true);
  52. entityContainer.addContainerProperty("assignee", String.class, "", true, true);
  53. whereParameters = new HashMap<String, Object>();
  54. whereParameters.put("name", nameFilter);
  55. entityContainer.filter("e.name=:name", whereParameters);
  56. table.setContainerDataSource(entityContainer);
  57. ....
  58. [[how-to-use-beanqueryfactory]]
  59. How to Use BeanQueryFactory
  60. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  61. `BeanQueryFactory` and `AbstractBeanQuery` are used to implement queries
  62. saving and loading JavaBeans.
  63. The `BeanQueryFactory` is used as follows with the Vaadin table. Usage of
  64. `queryConfiguration` is optional and enables passing objects to the
  65. constructed queries:
  66. [source,java]
  67. ....
  68. Table table = new Table();
  69. BeanQueryFactory<TaskBeanQuery> queryFactory = new
  70. BeanQueryFactory<TaskBeanQuery>(TaskBeanQuery.class);
  71. Map<String,Object> queryConfiguration = new HashMap<String,Object>();
  72. queryConfiguration.put("taskService",new TaskService());
  73. queryFactory.setQueryConfiguration(queryConfiguration);
  74. LazyQueryContainer container = new LazyQueryContainer(queryFactory,50);
  75. table.setContainerDataSource(container);
  76. ....
  77. Here is a simple example of `AbstractBeanQuery` implementation:
  78. [source,java]
  79. ....
  80. public class TaskBeanQuery extends AbstractBeanQuery<Task> {
  81. public TaskBeanQuery(QueryDefinition definition,
  82. Map<String, Object> queryConfiguration, Object[] sortPropertyIds,
  83. boolean[] sortStates) {
  84. super(definition, queryConfiguration, sortPropertyIds, sortStates);
  85. }
  86. @Override
  87. protected Task constructBean() {
  88. return new Task();
  89. }
  90. @Override
  91. public int size() {
  92. TaskService taskService =
  93. (TaskService)queryConfiguration.get("taskService");
  94. return taskService.countTasks();
  95. }
  96. @Override
  97. protected List<Task> loadBeans(int startIndex, int count) {
  98. TaskService taskService =
  99. (TaskService)queryConfiguration.get("taskService");
  100. return taskService.loadTasks(startIndex, count, sortPropertyIds, sortStates);
  101. }
  102. @Override
  103. protected void saveBeans(List<Task> addedTasks, List<Task> modifiedTasks,
  104. List<Task> removedTasks) {
  105. TaskService taskService =
  106. (TaskService)queryConfiguration.get("taskService");
  107. taskService.saveTasks(addedTasks, modifiedTasks, removedTasks);
  108. }
  109. }
  110. ....
  111. [[how-to-implement-custom-query-and-queryfactory]]
  112. How to Implement Custom Query and QueryFactory?
  113. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  114. `QueryFactory` instantiates new query whenever sort state changes or
  115. refresh is requested. Query can construct for example named JPA query in
  116. constructor. Data loading starts by invocation of `Query.size()` method
  117. and after this data is loaded in batches by invocations of
  118. `Query.loadItems()`.
  119. Please remember that the idea is to load data in batches. You do not
  120. need to load the entire data set to memory. If you do that you are
  121. better of with some other container implementation like
  122. `BeanItemContainer`. To be able to load database in batches you need your
  123. storage to provide you with the result set size and ability to load rows
  124. in batches as illustrated by the following pseudo code:
  125. [source,java]
  126. ....
  127. int countObjects(SearchCriteria searchCriteria);
  128. List<Object> getObjects(SearchCriteria searchCriteria, int startIndex, int batchSize);
  129. ....
  130. Here is simple read only JPA example to illustrate the idea. You can
  131. find further examples from add-on page.
  132. [source,java]
  133. ....
  134. package com.logica.portlet.example;
  135. import javax.persistence.EntityManager;
  136. import org.vaadin.addons.lazyquerycontainer.Query;
  137. import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
  138. import org.vaadin.addons.lazyquerycontainer.QueryFactory;
  139. public class MovieQueryFactory implements QueryFactory {
  140. private EntityManager entityManager;
  141. private QueryDefinition definition;
  142. public MovieQueryFactory(EntityManager entityManager) {
  143. super();
  144. this.entityManager = entityManager;
  145. }
  146. @Override
  147. public void setQueryDefinition(QueryDefinition definition) {
  148. this.definition = definition;
  149. }
  150. @Override
  151. public Query constructQuery(Object[] sortPropertyIds, boolean[] sortStates) {
  152. return new MovieQuery(entityManager,definition,sortPropertyIds,sortStates);
  153. }
  154. }
  155. ....
  156. [source,java]
  157. ....
  158. package com.logica.portlet.example;
  159. import java.util.ArrayList;
  160. import java.util.List;
  161. import javax.persistence.EntityManager;
  162. import org.vaadin.addons.lazyquerycontainer.Query;
  163. import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
  164. import com.logica.example.jpa.Movie;
  165. import com.vaadin.data.Item;
  166. import com.vaadin.data.util.BeanItem;
  167. public class MovieQuery implements Query {
  168. private EntityManager entityManager;
  169. private QueryDefinition definition;
  170. private String criteria = "";
  171. public MovieQuery(EntityManager entityManager,
  172. QueryDefinition definition,
  173. Object[] sortPropertyIds,
  174. boolean[] sortStates) {
  175. super();
  176. this.entityManager = entityManager;
  177. this.definition = definition;
  178. for(int i=0;i<sortPropertyIds.length;i++) {
  179. if(i==0) {
  180. criteria = " ORDER BY";
  181. } else {
  182. criteria+ = ",";
  183. }
  184. criteria += " m." + sortPropertyIds[i];
  185. if(sortStates[i]) {
  186. criteria += " ASC";
  187. }
  188. else {
  189. criteria += " DESC";
  190. }
  191. }
  192. }
  193. @Override
  194. public Item constructItem() {
  195. return new BeanItem<Movie>(new Movie());
  196. }
  197. @Override
  198. public int size() {
  199. javax.persistence.Query query = entityManager.
  200. createQuery("SELECT count(m) from Movie as m");
  201. return (int)((Long) query.getSingleResult()).longValue();
  202. }
  203. @Override
  204. public List<Item> loadItems(int startIndex, int count) {
  205. javax.persistence.Query query = entityManager.
  206. createQuery("SELECT m from Movie as m" + criteria);
  207. query.setFirstResult(startIndex);
  208. query.setMaxResults(count);
  209. List<Movie> movies=query.getResultList();
  210. List<Item> items=new ArrayList<Item>();
  211. for(Movie movie : movies) {
  212. items.add(new BeanItem<Movie>(movie));
  213. }
  214. return items;
  215. }
  216. @Override
  217. public void saveItems(List<Item> addedItems, List<Item> modifiedItems,
  218. List<Item> removedItems) {
  219. throw new UnsupportedOperationException();
  220. }
  221. @Override
  222. public boolean deleteAllItems() {
  223. throw new UnsupportedOperationException();
  224. }
  225. }
  226. ....
  227. [[how-to-implement-editable-table]]
  228. How to Implement Editable Table?
  229. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  230. First you need to implement the `Query.saveItems()` method. After this you
  231. need to set some of the properties editable in your items and set table
  232. in editable mode as well. After user has made changes you need to call
  233. `container.commit()` or `container.discard()` to commit or rollback
  234. respectively. Please find complete examples of table handing and
  235. editable JPA query from add-on page.
  236. [[how-to-use-debug-properties]]
  237. How to Use Debug Properties?
  238. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  239. LQC provides set of debug properties which give information about
  240. response times, number of queries constructed and data batches loaded.
  241. To use these properties the items used need to contain these properties
  242. with correct ids and types. If you use dynamic items you can defined
  243. them in the query definition and add them on demand in the query
  244. implementation.
  245. [source,java]
  246. ....
  247. container.addContainerProperty(LazyQueryView.DEBUG_PROPERTY_ID_QUERY_INDEX, Integer.class, 0, true, false);
  248. container.addContainerProperty(LazyQueryView.DEBUG_PROPERTY_ID_BATCH_INDEX, Integer.class, 0, true, false);
  249. container.addContainerProperty(LazyQueryView.DEBUG_PROPERTY_ID_BATCH_QUERY_TIME, Integer.class, 0, true, false);
  250. ....
  251. [[how-to-use-row-status-indicator-column-in-table]]
  252. How to Use Row Status Indicator Column in Table?
  253. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  254. When creating editable tables LCQ provides
  255. `QueryItemStatusColumnGenerator` which can be used to generate the status
  256. column cells to the table. In addition you need to have the status
  257. property in your items. If your items respect the query definition you
  258. can implement this as follows:
  259. [source,java]
  260. ....
  261. container.addContainerProperty(LazyQueryView.PROPERTY_ID_ITEM_STATUS,
  262. QueryItemStatus.class, QueryItemStatus.None, true, false);
  263. ....
  264. [[how-to-use-status-column-and-debug-columns-with-beans]]
  265. How to Use Status Column and Debug Columns with Beans
  266. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  267. Here is example query implementation which shows how JPA and beans can
  268. be used together with status and debug properties:
  269. [source,java]
  270. ....
  271. package org.vaadin.addons.lazyquerycontainer.example;
  272. import java.beans.BeanInfo;
  273. import java.beans.Introspector;
  274. import java.beans.PropertyDescriptor;
  275. import java.util.ArrayList;
  276. import java.util.List;
  277. import javax.persistence.EntityManager;
  278. import org.vaadin.addons.lazyquerycontainer.CompositeItem;
  279. import org.vaadin.addons.lazyquerycontainer.Query;
  280. import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
  281. import com.vaadin.data.Item;
  282. import com.vaadin.data.util.BeanItem;
  283. import com.vaadin.data.util.ObjectProperty;
  284. public class TaskQuery implements Query {
  285. private EntityManager entityManager;
  286. private QueryDefinition definition;
  287. private String criteria=" ORDER BY t.name ASC";
  288. public TaskQuery(EntityManager entityManager, QueryDefinition definition,
  289. Object[] sortPropertyIds, boolean[] sortStates) {
  290. super();
  291. this.entityManager = entityManager;
  292. this.definition = definition;
  293. for(int i=0; i<sortPropertyIds.length; i++) {
  294. if(i==0) {
  295. criteria = " ORDER BY";
  296. } else {
  297. criteria+ = ",";
  298. }
  299. criteria += " t." + sortPropertyIds[i];
  300. if(sortStates[i]) {
  301. criteria += " ASC";
  302. }
  303. else {
  304. criteria += " DESC";
  305. }
  306. }
  307. }
  308. @Override
  309. public Item constructItem() {
  310. Task task=new Task();
  311. try {
  312. BeanInfo info = Introspector.getBeanInfo( Task.class );
  313. for ( PropertyDescriptor pd : info.getPropertyDescriptors() ) {
  314. for(Object propertyId : definition.getPropertyIds()) {
  315. if(pd.getName().equals(propertyId)) {
  316. pd.getWriteMethod().invoke(task,
  317. definition.getPropertyDefaultValue(propertyId));
  318. }
  319. }
  320. }
  321. } catch(Exception e) {
  322. throw new RuntimeException("Error in bean property population");
  323. }
  324. return toItem(task);
  325. }
  326. @Override
  327. public int size() {
  328. javax.persistence.Query query = entityManager.createQuery(
  329. "SELECT count(t) from Task as t");
  330. return (int)((Long) query.getSingleResult()).longValue();
  331. }
  332. @Override
  333. public List<Item> loadItems(int startIndex, int count) {
  334. javax.persistence.Query query = entityManager.createQuery(
  335. "SELECT t from Task as t" + criteria);
  336. query.setFirstResult(startIndex);
  337. query.setMaxResults(count);
  338. List<Task> tasks=query.getResultList();
  339. List<Item> items=new ArrayList<Item>();
  340. for(Task task : tasks) {
  341. items.add(toItem(task));
  342. }
  343. return items;
  344. }
  345. @Override
  346. public void saveItems(List<Item> addedItems, List<Item> modifiedItems,
  347. List<Item> removedItems) {
  348. entityManager.getTransaction().begin();
  349. for(Item item : addedItems) {
  350. entityManager.persist(fromItem(item));
  351. }
  352. for(Item item : modifiedItems) {
  353. entityManager.persist(fromItem(item));
  354. }
  355. for(Item item : removedItems) {
  356. entityManager.remove(fromItem(item));
  357. }
  358. entityManager.getTransaction().commit();
  359. }
  360. @Override
  361. public boolean deleteAllItems() {
  362. throw new UnsupportedOperationException();
  363. }
  364. private Item toItem(Task task) {
  365. BeanItem<Task> beanItem= new BeanItem<Task>(task);
  366. CompositeItem compositeItem=new CompositeItem();
  367. compositeItem.addItem("task", beanItem);
  368. for(Object propertyId : definition.getPropertyIds()) {
  369. if(compositeItem.getItemProperty(propertyId)==null) {
  370. compositeItem.addItemProperty(propertyId, new ObjectProperty(
  371. definition.getPropertyDefaultValue(propertyId),
  372. definition.getPropertyType(propertyId),
  373. definition.isPropertyReadOnly(propertyId)));
  374. }
  375. }
  376. return compositeItem;
  377. }
  378. private Task fromItem(Item item) {
  379. return (Task)((BeanItem)(((CompositeItem)item).getItem("task"))).getBean();
  380. }
  381. }
  382. ....