Generating Java Code for Aspect Models
Java code can be generated from an Aspect model in two ways:
-
The generated code represents the Aspect payload. Aspects and Entities become Java classes; their Properties become fields in the classes. Characteristics are not first-class elements, but are implicitly represented by the usage of corresponding data types (e.g. using
java.util.Setas the type for theSetCharacteristic of a Property) orjavax.validationannotations. The generated classes can be used in a straightforward fashion, but they do not contain information about the underlying Aspect model such as its version number. Parts of the Aspect model that have no representation in its corresponding JSON payload are not part of those classes either, in particular descriptions and preferred names. These classes are called POJOs (Plain Old Java Objects), as they do not contain logic but serve mainly as data containers. -
The generated code represents the Aspect model itself: It is a type-safe variant of the model and includes every information that is also present in the model such as Characteristics, descriptions including language tags and original XSD data types. It is however not intended to store payload corresponding to an Aspect. Theses classes are called static meta classes, because they are created at compile time (static) and talk about the structure of the information, not the information itself (meta).
Depending on the use case, you would either use one or both of the types simultaneously.
To include the Java generator, use the following dependencies:
-
Maven
-
Gradle Groovy DSL
-
Gradle Kotlin DSL
<dependency>
<groupId>org.eclipse.esmf</groupId>
<artifactId>esmf-aspect-model-java-generator</artifactId>
<version>2.16.2</version>
</dependency>
implementation 'org.eclipse.esmf:esmf-aspect-model-java-generator:2.16.2'
implementation("org.eclipse.esmf:esmf-aspect-model-java-generator:2.16.2")
Type Mapping
In the Java code generated from an Aspect model, the scalar Aspect model data types are mapped to native Java types. The following table lists the correspondences.
| Aspect model type | Java native type |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Generating POJOs
POJO generation is straightforward; there are two minor differences to the generation of documentation artifacts.
Firstly, when instantiating the generator, you pass a flag indicating whether
Jackson annotations should be generated in the class. Secondly, the name
mapping function passed to the generation method takes a QualifiedName instead of a String, so that you can decide how
to handle the package structure of the class.
By default, POJO classes are generated without setters. If setters are desired, use enableSetters( true ) on the
generator config. Three setter styles are supported:
| Setter style | Example output |
|---|---|
|
|
|
|
|
|
The FLUENT_* styles allow for method chaining, so that POJO instances can be written in a more compact way.
Show used imports
import org.eclipse.esmf.aspectmodel.java.JavaCodeGenerationConfig;
import org.eclipse.esmf.aspectmodel.java.JavaCodeGenerationConfigBuilder;
import org.eclipse.esmf.aspectmodel.java.pojo.AspectModelJavaGenerator;
import org.eclipse.esmf.aspectmodel.loader.AspectModelLoader;
import org.eclipse.esmf.metamodel.AspectModel;
// AspectModel as returned by the AspectModelLoader
final AspectModel aspectModel = // ...
final JavaCodeGenerationConfig config = JavaCodeGenerationConfigBuilder.builder()
.enableJacksonAnnotations( true )
.packageName( "com.example.mycompany" ) // if left out, package is taken from Aspect's namespace
.enableSetters( true ) // if left out, setters are not generated
.setterStyle( JavaCodeGenerationConfig.SetterStyle.FLUENT ) // if left out, "STANDARD" setter style is used
.build();
final AspectModelJavaGenerator generator = new AspectModelJavaGenerator( aspectModel.aspect(), config );
generator.generate( qualifiedName -> {
// Create an output stream for the given qualified Java class name
} );
Generating Static Meta Classes
For the generation of static meta classes, consider the following example:
Show used imports
import org.eclipse.esmf.aspectmodel.java.JavaCodeGenerationConfig;
import org.eclipse.esmf.aspectmodel.java.JavaCodeGenerationConfigBuilder;
import org.eclipse.esmf.aspectmodel.java.metamodel.StaticMetaModelJavaGenerator;
import org.eclipse.esmf.aspectmodel.loader.AspectModelLoader;
import org.eclipse.esmf.metamodel.AspectModel;
// AspectModel as returned by the AspectModelLoader
final AspectModel aspectModel = // ...
final JavaCodeGenerationConfig config = JavaCodeGenerationConfigBuilder.builder()
.enableJacksonAnnotations( true )
.packageName( "com.example.mycompany" ) // if left out, package is taken from Aspect's namespace
.build();
final StaticMetaModelJavaGenerator generator = new StaticMetaModelJavaGenerator( aspectModel.aspect(), config );
generator.generate( qualifiedName -> {
// Create an output stream for the given qualified Java class name
} );
To use the generated static meta classes, you need the following additional dependency:
-
Maven
-
Gradle Groovy DSL
-
Gradle Kotlin DSL
<dependency>
<groupId>org.eclipse.esmf</groupId>
<artifactId>esmf-aspect-static-meta-model-java</artifactId>
<version>2.16.2</version>
</dependency>
implementation 'org.eclipse.esmf:esmf-aspect-static-meta-model-java:2.16.2'
implementation("org.eclipse.esmf:esmf-aspect-static-meta-model-java:2.16.2")
Providing Custom Macros for Code Generation
It is possible to change predefined sections of the generated classes by providing custom Velocity templates; see the Velocity User Guide for more information. The custom macros must be defined in a single template file. The path to the template file as well as its name may be passed as arguments to the code generation, e.g. using the SAMM-CLI.
Custom macros may be provided for the following sections:
| Section | Macro Name | Default Macro Provided |
|---|---|---|
Copyright Licence Header |
fileHeader |
| When using custom macros, macros for all sections above must be provided. |
Example:
#macro( fileHeader )
/*
* Copyright (c) $currentYear.getValue() Test Inc. All rights reserved.
*/
#end
Generating SQL for Aspect Models
Using the Aspect Model SQL generator, an SQL script can be generated that sets up a table for data corresponding to the Aspect. The current implementation provides support for the Databricks SQL and PostgreSQL dialects and denormalized and normalized mapping strategies.
The following sections explain how the mapping strategies differ based on the following example model:
:Maintenance a samm:Aspect ;
samm:description "Machine maintenance information"@en ;
samm:properties ( :lastService ) .
:lastService a samm:Property ;
samm:characteristic [
a samm-c:SingleEntity ;
samm:dataType :ServiceRecord ;
] .
:ServiceRecord a samm:Entity ;
samm:properties (
:serviceDate
:technicianName
:durationOfDeployment
) .
:serviceDate a samm:Property ;
samm:description "When was the maintenance performed"@en ;
samm:characteristic samm-c:Timestamp .
:technicianName a samm:Property ;
samm:description "Who performed the maintenance"@en ;
samm:characteristic samm-c:Text .
:durationOfDeployment a samm:Property ;
samm:description "How long did the maintenance take"@en ;
samm:characteristic [
a samm-c:Duration ;
samm:dataType xsd:decimal ;
samm-c:unit unit:hour ;
] .
Denormalized Mapping Strategy
The denormalized mapping strategy creates a single table for an Aspect that contains one column for each Property used in the Aspect Model or any of its transitively referenced Entities. Column names are built by concatenating Property names from the parent element with Property elements from the child element.
By following the denormalized mapping strategy, the SQL code generated for the example model looks like the following:
-
Databricks SQL
-
PostgreSQL
CREATE TABLE IF NOT EXISTS maintenance ( (1)
last_service__service_date TIMESTAMP NOT NULL COMMENT 'When was the maintenance performed', (2)
last_service__technician_name STRING NOT NULL COMMENT 'Who performed the maintenance', (3)
last_service__duration_of_deployment DECIMAL(10,0) NOT NULL COMMENT 'How long did the maintenance take'
)
COMMENT 'Machine maintenance information' (4)
TBLPROPERTIES ('x-samm-aspect-model-urn'='urn:samm:org.eclipse.esmf.examples:1.0.0#Maintenance'); (5)
| 1 | The table name is created by translating the Aspect name from camel case to snake case. |
| 2 | Column names are concatenated, following the path from the root element. If all Properties on
the path (in this case lastService on Maintenance and serviceDate on ServiceRecord) are
mandatory (not marked optional), a NOT NULL constraint is added. Column comments contain the
description from the original Propery’s samm:description attribute. |
| 3 | SQL types are derived from the used Characteristic’s samm:dataType, see Databricks Type Mapping. |
| 4 | A table comment is added with the Aspect’s samm:description. |
| 5 | A table property indicating the original source of the table structure is added. |
CREATE TABLE IF NOT EXISTS maintenance ( (1)
last_service__service_date TIMESTAMP NOT NULL, (2)
last_service__technician_name TEXT NOT NULL, (3)
last_service__duration_of_deployment NUMERIC(10,0) NOT NULL
);
COMMENT ON TABLE maintenance IS 'Machine maintenance information'; (4)
COMMENT ON COLUMN maintenance.last_service__service_date IS 'When was the maintenance performed';
COMMENT ON COLUMN maintenance.last_service__technician_name IS 'Who performed the maintenance';
COMMENT ON COLUMN maintenance.last_service__duration_of_deployment IS 'How long did the maintenance take';
-- x-samm-aspect-model-urn: urn:samm:org.eclipse.esmf.examples:1.0.0#Maintenance
| 1 | The table name is created by translating the Aspect name from camel case to snake case. |
| 2 | Column names are concatenated, following the path from the root element. If all Properties on
the path (in this case lastService on Maintenance and serviceDate on ServiceRecord) are
mandatory (not marked optional), a NOT NULL constraint is added. Column comments contain the
description from the original Propery’s samm:description attribute. |
| 3 | SQL types are derived from the used Characteristic’s samm:dataType, see PostgreSQL Type Mapping. |
| 4 | A table comment is added with the Aspect’s samm:description. |
Normalized Mapping Strategy
In the normalized mapping strategy, a separate table is created for each structure element (Aspect or Entity). Tables have numeric primary keys and are related to each other using relationship tables. Structure tables are emitted before collection and relationship tables so that referenced tables exist when their foreign keys are created.
By following the normalized mapping strategy, the SQL code generated for the example model looks like the following:
-
Databricks SQL
-
PostgreSQL
CREATE TABLE IF NOT EXISTS service_record ( (1)
_id BIGINT NOT NULL PRIMARY KEY,
service_date TIMESTAMP NOT NULL COMMENT 'When was the maintenance performed',
technician_name STRING NOT NULL COMMENT 'Who performed the maintenance',
duration_of_deployment DECIMAL(10,0) NOT NULL COMMENT 'How long did the maintenance take'
)
TBLPROPERTIES ('x-samm-aspect-model-urn'='urn:samm:org.eclipse.esmf.examples:1.0.0#ServiceRecord');
CREATE TABLE IF NOT EXISTS maintenance (
_id BIGINT NOT NULL PRIMARY KEY (2)
)
COMMENT 'Machine maintenance information'
TBLPROPERTIES ('x-samm-aspect-model-urn'='urn:samm:org.eclipse.esmf.examples:1.0.0#Maintenance');
CREATE TABLE IF NOT EXISTS service_record___references ( (3)
_id_source BIGINT NOT NULL,
_id_target BIGINT NOT NULL,
property_name STRING NOT NULL, (4)
FOREIGN KEY (_id_source) REFERENCES maintenance(_id),
FOREIGN KEY (_id_target) REFERENCES service_record(_id)
)
| 1 | A separate table is created for the ServiceRecord Entity. |
| 2 | The table has an id column as well as columns for scalar Properties. Properties with collection Characteristics or which use Entities as data types don’t appear. |
| 3 | A references table connects the source (maintenance) with the target (service_record). |
| 4 | Entries in the references table explicitly mention the source’s property name, since multiple properties may refer to the same target structure. In the example, this column would always contain "lastService". |
CREATE TABLE IF NOT EXISTS service_record ( (1)
_id BIGINT NOT NULL PRIMARY KEY,
service_date TIMESTAMP NOT NULL,
technician_name TEXT NOT NULL,
duration_of_deployment NUMERIC(10,0) NOT NULL
);
COMMENT ON COLUMN service_record.service_date IS 'When was the maintenance performed';
COMMENT ON COLUMN service_record.technician_name IS 'Who performed the maintenance';
COMMENT ON COLUMN service_record.duration_of_deployment IS 'How long did the maintenance take';
-- x-samm-aspect-model-urn: urn:samm:org.eclipse.esmf.examples:1.0.0#ServiceRecord
CREATE TABLE IF NOT EXISTS maintenance ( (2)
_id BIGINT NOT NULL PRIMARY KEY
);
COMMENT ON TABLE maintenance IS 'Machine maintenance information';
-- x-samm-aspect-model-urn: urn:samm:org.eclipse.esmf.examples:1.0.0#Maintenance
CREATE TABLE IF NOT EXISTS service_record___references ( (3)
_id_source BIGINT NOT NULL REFERENCES maintenance (_id),
_id_target BIGINT NOT NULL REFERENCES service_record (_id),
property_name TEXT NOT NULL (4)
);
| 1 | A separate table is created for the ServiceRecord Entity. |
| 2 | The table has an id column as well as columns for scalar Properties. Properties with collection Characteristics or which use Entities as data types don’t appear. |
| 3 | A references table connects the source (maintenance) with the target (service_record). |
| 4 | Entries in the references table explicitly mention the source’s property name, since multiple properties may refer to the same target structure. In the example, this column would always contain "lastService". |
Code Example
The following code demonstrates how to generate SQL for an Aspect, using the denormalized mapping
strategy. The example uses the Databricks SQL dialect; alternatively you can use the equivalent
Postgres-specific classes to work with PostgreSQL instead: PostgreSqlGenerationConfig,
PostgreSqlType, PostgreSqlConstraint and so on.
Show used imports
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import org.eclipse.esmf.aspectmodel.generator.sql.AspectModelSqlGenerator;
import org.eclipse.esmf.aspectmodel.generator.sql.SqlGenerationConfig;
import org.eclipse.esmf.aspectmodel.generator.sql.SqlGenerationConfigBuilder;
import org.eclipse.esmf.aspectmodel.generator.sql.databricks.DatabricksColumnDefinitionBuilder;
import org.eclipse.esmf.aspectmodel.generator.sql.databricks.DatabricksConstraint;
import org.eclipse.esmf.aspectmodel.generator.sql.databricks.DatabricksSqlGenerationConfig;
import org.eclipse.esmf.aspectmodel.generator.sql.databricks.DatabricksSqlGenerationConfigBuilder;
import org.eclipse.esmf.aspectmodel.generator.sql.databricks.DatabricksType;
import org.eclipse.esmf.aspectmodel.loader.AspectModelLoader;
import org.eclipse.esmf.metamodel.AspectModel;
// AspectModel as returned by the AspectModelLoader
final AspectModel aspectModel = // ...
final DatabricksSqlGenerationConfig databricksSqlGenerationConfig =
DatabricksSqlGenerationConfigBuilder.builder()
.commentLanguage( Locale.ENGLISH ) // optional
.includeTableComment( true ) // optional
.includeColumnComments( true ) // optional
.decimalPrecision( 10 ) // optional
.decimalScale( 0 ) // optional
.customColumns( List.of( // optional
DatabricksColumnDefinitionBuilder.builder()
.name( "custom_column" )
.type( new DatabricksType.DatabricksArray( DatabricksType.STRING ) )
.nullable( false )
.comment( Optional.of( "Custom column" ) )
.build() ) )
.tableConstraints( List.of( // optional
new DatabricksConstraint.Unique( "custom_column" ) ) )
.build();
final SqlGenerationConfig sqlGenerationConfig =
SqlGenerationConfigBuilder.builder()
.dialect( SqlGenerationConfig.Dialect.DATABRICKS )
.mappingStrategy( SqlGenerationConfig.MappingStrategy.DENORMALIZED )
.dialectSpecificConfig( databricksSqlGenerationConfig )
.build();
final String result = new AspectModelSqlGenerator( aspectModel.aspect(), sqlGenerationConfig ).getContent();
The dialect-specific generation configuration accepts tableConstraints, a list of SQL table
constraint definitions. Each definition is inserted verbatim after the column definitions. The
caller is responsible for using valid syntax and column names for the selected dialect; the
generator does not validate them.
When generating SQL using the normalized mapping strategy and you want to include custom columns
or constraints, you need to configure to which table they should apply. In the dialect-specific
SqlGenerationConfigBuilder, instead of customColumns() and tableConstraints() use
customColumnsPerTable() and tableConstraintsPerTable(), respectively:
final DatabricksSqlGenerationConfig databricksSqlGenerationConfig =
DatabricksSqlGenerationConfigBuilder.builder()
.tableConstraintsPerTable( Map.of(
"movement",
List.of( new DatabricksConstraint.Unique( "speed" ) ) ) )
.build();
final SqlGenerationConfig sqlGenerationConfig =
SqlGenerationConfigBuilder.builder()
.dialect( SqlGenerationConfig.Dialect.DATABRICKS )
.mappingStrategy( SqlGenerationConfig.MappingStrategy.NORMALIZED )
.dialectSpecificConfig( databricksSqlGenerationConfig )
.build();
final String result = new AspectModelSqlGenerator( aspectModel.aspect(), sqlGenerationConfig ).getContent();
Databricks Type Mapping
Data types in the Aspect Model are mapped to Databricks types using the following correspondences:
| Aspect model type | Databricks SQL type | Note |
|---|---|---|
|
|
|
|
|
|
|
|
While xsd:decimal is by definition unbounded, DECIMAL’s default precision is 10 digits and can be up to 38. if we assume values larger than that can appear in the data, the Aspect Models using xsd:decimal should also use a samm-c:FixedPointConstraint accordingly. |
|
|
As opposed to xsd:int, xsd:integer has arbitrary precision, i.e. DECIMAL is needed. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The fixed precision of 20 accommodates the maximum value 18446744073709551615, independently of the configured decimal precision. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
PostgreSQL Type Mapping
To generate PostgreSQL, use SqlGenerationConfig.Dialect.POSTGRESQL and a
PostgreSqlGenerationConfig. Collections of scalar values are represented as PostgreSQL arrays.
Table and column descriptions are emitted using COMMENT ON TABLE and COMMENT ON COLUMN.
| Aspect model type | PostgreSQL type | Note |
|---|---|---|
|
|
|
|
|
|
|
|
The configured precision and scale are used. |
|
|
The configured precision is used. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The fixed precision of 20 accommodates the maximum value 18446744073709551615, independently of the configured decimal precision. |
|
|
The configured precision is used. |
|
|
|
|
|