Additional JPA annotations - View mapping

When managing your data, you may build your entity on a single view for which you create a DataDescriptor . We can display this data structure on the interface, but we may encounter problems when modifying the data, because some of the data in our data record may not be represented in the same table.

To solve this problem, the concept of view mapping was created in the JBStrap framework, which means mapping the fields of a view to one or more other tables. Columns that have been mapped in this way will not be saved or modified in the view but the specified column of the entity specified in the map. This will allow the source of the displayed data to differ from the save location.

A field in a view can be mapped to fields in several other entities to manage table relationships. Thus, if a view is based on three tables, one of which is the master record and two more detail records, you can map the Id field so that the detail records can be automatically saved and modified accordingly.

Let us look at the above concept through an example. In this example, we want to store an address. Our title record is listed as a master record in the example and has two detail records representing the city and state. In this example we use the following data structure:

For each of the three tables, we construct the required entity classes in the usual way and then create the view by joining the three tables. Below is the source code for the view:
We build the following entity class based on the created view:

If we did not use view mapping in the example, we could only read data from the VAddress entity. If we were to save it, it would result in an error. Because we used view mapping annotations, we can also save data to the entity, which will be automatically directed to the appropriate column of the corresponding table.

By redirecting the id column to the id column in the detail tables, the automatically generated ID is saved to the detail table when a new record is saved.

ViewEntity

You must place this annotation on the entity that contains redirected fields. Unless we annotate the entity, the MappedField annotations placed on the fields will not work.

MappedField

This annotation must be placed on the field whose value you want to redirect to one or more other tables. If you want to redirect the value of a field to several other tables, the annotation must be repeatedly placed on the field.

The annotation must have two parameters:

  • clazz : The parameter must specify the entity class to which the data is redirected.
  • fieldName : The parameter must specify the field to which the data is redirected.

If you specify a field in the fieldName parameter that does not exist in the class specified in the class parameter, the save process will throw an exception and the save will not take place.