Menu

Create a Query Service

Ralph

A controller extending the DbListController has to provide a QueryService.
This service implements functionality to query data from the database and map the entities to the view objects.

Lets create a simple service to perform a query:

  final Service<Integer> service = new Service<Integer>() {

    @Override
    protected Task<Integer> createTask() {
      return new Task<Integer>() {

        @SuppressWarnings("unchecked")
        @Override
        protected Integer call() throws Exception {
          int listElements = 0;
          PersonListController<VoPerson> controller = (PersonListController<VoPerson>) PersonListController.this;

          TypedQuery<Person> searchQuery = null;
          EntityManager entityManager = PersistenceManager.getEntityManager();
          searchQuery = entityManager.createNamedQuery("Person.getAll", Person.class);

          List<VoPerson> resultList = new ArrayList<>(searchQuery.getResultList().size());
          // create a view object factory ...
          EntityViewObjectMapper<V, Person> factory = EntityViewObjectMapperFactory.getMapper(VoPerson.class,
              Person.class);
          // ... and create the list of view objects
          resultList = (List<VoPerson>) factory.getViewObjectList(searchQuery.getResultList());
          listElements = resultList.size();
          // push the list of view objects to the controller
          controller.setViewObjects(resultList);
          return Integer.valueOf(listElements);
        }
      };
    }
  };

The important statement is to call EntityViewObjectMapperFactory.getMapper(). The method provides a mapping functionality between the entity class and the view object class. For each call of this method you get the same mapper if the Vo-class and the Entity-class are the same. For new combinations of Vo- and entity classes you get a new mapper.
To push the list of view objects to the JavaFX table view simply call controller.setViewObjects(list).

The mapping between view object classes and entity classes are simply done by calling the opposite get/set methods of the objects. Therefore it is important to implement the matching methods in view objects as well as in the entity classes.


Related

Wiki: Create a Controller

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.