Reference

Template syntax

The body and install path of a code generation template are written in Apache Velocity syntax. This page collects, in tables, the values and helper functions a template can read. The screen where you create and edit templates is described in Template packs, and the screen where you generate code from templates in Generating source code.

At a glance

When you generate code, each template is rendered once per table. These are the values a template reads at that time.

NameContents
$entityThe entity of the table being generated: its name, list of fields, soft delete settings, and the entity variables defined by the pack
$fieldOne field (column) of the entity. Iterate with #foreach($field in $entity.fields)
$envThe pack's global variables, filled in by the project
$tableThe source table: table name, schema, list of PK columns, list of columns
$projectConfigThe project settings. The part used for code generation is the audit settings (auditConfig)
$databaseInfoThe product name and version of the target DBMS
$paidWhether the current account is on a paid plan (true/false)
$codegen, $typesHelper functions for renaming, DBMS checks, picking PKs, type checks and more
$java, $ts, $pyLanguage-specific helpers. You can generate code with $codegen and $types alone
$dateThe standard Velocity date tool (DateTool)

Variables defined in the pack's Entity Variables table and Field Variables table are lifted directly under $entity and $field just before rendering. If you define an entity variable subPackage, read it as $entity.subPackage. When a built-in value has the same name, the pack variable's value wins.

Basic syntax

SyntaxMeaning
$name, ${name}Writes a value. When text follows immediately, wrap it in braces, as in ${entity.name}Service
$!nameWrites empty text when there is no value. With $name, a missing value prints the text $name as is
#set($v = …)Assigns a value to a variable
#if(…), #elseif(…), #else, #endWrites depending on a condition
#foreach($x in $list) … #endIterates a list. Inside, use $foreach.count (from 1), $foreach.index (from 0) and $foreach.hasNext
[1..3], [], {'k': 'v'}Creates a range, a list or a map directly
## …, #* … *#Comments. They do not appear in the output

Java string methods (toUpperCase(), startsWith(), substring() and so on) and list and map methods (size(), add() and so on) work as usual.

Example: an entity class

A template that turns the demo shop's customer table (customer_id, email, name, grade, created_at) into a Java class.

package ${env.package.core}.domain;

#foreach($import in $java.imports())
import $import;
#end

/** $!entity.comment */
public class ${entity.name} {
#foreach($field in $entity.fields)
#if($codegen.isPk($field.column))
    // PK
#end
    private $types.typeOf($field) ${field.name};
#end
}
  • The field name ($field.name) is the column name with the project's naming rules (Renamer) applied. Depending on the rules, customer_id becomes a name such as customerId.
  • $types.typeOf($field) is the short name (String for java.lang.String) of the type chosen by the pack's type mapping.
  • $env.package.core assumes the pack defines a global variable with the key package.core and the project has filled in its value.

Entity

$entity is the entity of the table being generated. Name variants are computed in advance.

PropertyContents
nameThe entity name. Set in the code generation settings of the table tab (usually PascalCase, such as Customer)
commentThe table description
aliasThe alias
varlowerCamel of name. Example: orderItem
snakeLower, snakeUppersnake_case of name. Example: order_item, ORDER_ITEM
kebabLower, kebabUpperkebab-case of name. Example: order-item, ORDER-ITEM
fieldsThe list of fields. Iterate with #foreach
fieldMapA map from DB column name to field. Use it to find one field by column name
softDeleteThe soft delete settings (table below)
(entity variable keys)Entity variables defined by the pack. Example: $entity.subPackage

Soft delete settings

$entity.softDelete. When soft delete is not used or there is no flag column, only enabled being false is guaranteed. In the table below, "Automatic" marks values filled in from the column types at generation time.

PropertyContents
enabledWhether soft delete is used
flagColumnThe DB name of the deletion flag column
deletedValue, activeValueWhen the flag is not boolean, the values that mean deleted and not deleted (such as Y/N, 1/0)
dateColumnThe DB name of the deletion time column (optional)
dateFormatThe date format to store when the time column is a string
flagBooleanAutomatic. Whether the flag column is boolean
flagStringAutomatic. Whether the flag column is a string (whether to quote the value in SQL)
flagFieldAutomatic. The field name of the flag column
dateStringAutomatic. Whether the time column is a string
dateFieldAutomatic. The field name of the time column

Field

$field is one item of $entity.fields. It carries the field name, the resolved type and the source column.

PropertyContents
nameThe field name: the column name with the naming rules (Renamer) applied
commentThe field description
mappedTypeThe resolved type (table below). It reflects the type mapping of the pack being rendered and any per-column type override
defaultValueThe field's default value
deletedMarkWhether this field is the soft delete flag
metaAttributesThe list of META attributes. Each item has name and value. $codegen.getMetaAttribute() is easier to use
columnThe source DB column (table below)
(field variable keys)Field variables defined by the pack. Example: $field.customType

Resolved type

$field.mappedType.

PropertyContents
typeThe intermediate type. Example: M_LONG, M_STRING (see "Intermediate types and categories" below)
targetThe type in this pack's language. Example: java.lang.Long, number. To write it in code, $types.typeOf($field) is handier
categoryThe category: one of number, text, datetime, boolean, array, object, url

Source column

The main properties of $field.column, as read from the DB.

PropertyContents
nameThe DB column name
remarksThe column description
typeThe DB type. Example: VARCHAR, BIGINT
size, decimalDigitsLength and decimal digits
nullableWhether NULL is allowed
autoIncrementWhether it auto-increments
defaultValueThe DB default value

Other values

NamePropertyContents
$env(global variable keys)Values defined in the pack's Global Variables table and filled in by the project. If you split a key with dots, as in package.core, read it as $env.package.core. A variable left empty takes the default from its definition
$tablename, remarks, schemaName, databaseNameTable name, description, schema, database
$tableprimaryKeysThe list of DB names of the PK columns
$tablecolumnsThe list of source columns
$projectConfigauditConfig.auditTableThe audit reference table. Filled in only when it is a table of the same connection
$projectConfigauditConfig.creationAuthorList, creationDateList, lastModificationAuthorList, lastModificationDateListCandidate column names for creator, creation time, modifier and modification time. Use the $codegen audit functions rather than reading these directly
$databaseInfodatabaseProductNameThe DBMS product name (such as MariaDB). When the product name is unknown, the connection's DBMS type (such as SQLServer) is used instead. For branching, use functions such as $codegen.isMariaDB()
$databaseInfodatabaseProductVersionThe product version. Empty when unknown
$paidWhether the current account is on a paid plan

The audit settings are filled in on the Audit Table tab described in Generating source code.

Intermediate types and categories

NeoSQL first converts each DB column type into one of the intermediate types below, and the pack's type mapping then turns the intermediate type into a language type. Categories are used for checks such as $types.isDate($field).

CategoryIntermediate types
textM_STRING, M_CHAR, M_CLOB
numberM_INTEGER, M_LONG, M_BIGINTEGER, M_BYTE, M_DOUBLE, M_FLOAT, M_BIGDECIMAL
booleanM_BOOLEAN
datetimeM_LOCALDATE, M_LOCALTIME, M_LOCALDATETIME, M_ZONEDDATETIME, M_SQLDATE, M_UTILDATE, M_INSTANT, M_TIME, M_TIMESTAMP
arrayM_ARRAY, M_BYTES, M_BLOB
urlM_URL
objectM_REF, M_OBJECT

codegen functions

$codegen is a language-neutral helper.

Names and text

FunctionContents
$codegen.toLowerCamel(value)MyName → myName
$codegen.toUpperCamel(value)myProp → MyProp, my_prop → MyProp
$codegen.toUpperUnderscore(value)MyName → MY_NAME
$codegen.toPath(a, b, …)Replaces dots (.) in each argument with / and joins them into a path, skipping empty arguments. toPath('com.example', 'app') → com/example/app
$codegen.join(sep, a, b, …)Joins with the separator, skipping empty values. Repeated separators collapse into one
$codegen.replace(text, from, to)Replaces every from with to. Example: $codegen.replace('com.example', '.', '/') → com/example
$codegen.printIf(cond, value)value if cond is true, otherwise empty text
$codegen.printVelocityVar(value)Writes value in the form ${value}. Use it to leave Velocity notation in the generated output
$codegen.printIgnoreFirst(count, value)Empty text if count is 1, otherwise value. Use it with $foreach.count to drop the separator before the first item

DBMS checks and SQL

FunctionContents
$codegen.isOracle(), isMySQL(), isMariaDB(), isPostgreSql(), isMsSql()Whether the target DBMS is that one, judged by whether $databaseInfo.databaseProductName contains the name
$codegen.getColumnName(name)[name] for SQL Server, otherwise unchanged
$codegen.useSchemaPrefix()Whether the Use Schema Prefix option on the Schema tab of the connection settings is on
$codegen.getSchemaPrefix()schema. ([schema]. for SQL Server) when the Use Schema Prefix option is on, otherwise empty text
$codegen.hasSequence()Whether $entity.sequenceName is set, which happens when the pack defines an entity variable sequenceName
$codegen.getSelectKeyStatement()Returns SQL to read a new PK value for MyBatis selectKey. The returned SQL depends on the DBMS as listed below.
$codegen.getSelectKeyOrder()before for Oracle and PostgreSQL, after for SQL Server, MySQL and MariaDB, no value otherwise

$codegen.getSelectKeyStatement() returns SQL under these conditions:

  • On Oracle with a sequence name, it returns SELECT sequence.NEXTVAL FROM DUAL.
  • On PostgreSQL with a sequence name, it returns SELECT CURRVAL('sequence').
  • On SQL Server when the first PK column is auto-incrementing, it returns SELECT SCOPE_IDENTITY() AS id.
  • On MySQL or MariaDB when the first PK column is auto-incrementing, it returns SELECT LAST_INSERT_ID().
  • Otherwise, there is no value.

Picking PKs and fields

FunctionContents
$codegen.getPkAttr()The list of PK fields (in $table.primaryKeys order)
$codegen.getNonPkAttr()The list of non-PK fields
$codegen.isSinglePk()Whether the PK is a single column
$codegen.isSinglePkAndLongTypeAndNameIsId()Whether there is one PK named id whose intermediate type is M_LONG
$codegen.isPk($field.column)Whether the column is a PK
$codegen.getDeletedField(), hasDeletedField()The soft delete flag field (deletedMark) and whether it exists
$codegen.getMetaAttribute(name, $field)The value of a META attribute of the field. Empty text if absent

Audit columns

The candidate name lists are in $projectConfig.auditConfig, and name in these functions is a field name.

FunctionContents
$codegen.hasAuditTable()Whether the audit reference table was found on this connection
$codegen.hasCreated(), hasModified()Whether both the creator and creation time columns exist, and whether both the modifier and modification time columns exist
$codegen.isCreationAuthor(name), isCreationDate(name)Whether it is a creator or creation time candidate
$codegen.isModificationAuthor(name), isModificationDate(name)Whether it is a modifier or modification time candidate
$codegen.isCreationField(name), isModificationField(name)Whether it is a creation-side or modification-side column
$codegen.isAuditField(name), isAuditDateField(name)Whether it is any audit column, and whether it is one of the time columns

Validation keywords

FunctionContents
$codegen.validationsField($field)Returns the validation keywords for a field, according to the conditions below.
$codegen.validationsEntity($entity)The keywords of all fields, without duplicates

$codegen.validationsField($field) applies these conditions:

  • PK and audit fields return an empty list.
  • NOT NULL VARCHAR or VARCHAR2 columns add notblank.
  • Other NOT NULL columns add notnull.
  • VARCHAR or VARCHAR2 columns with a length greater than zero add utf8size, regardless of whether they are NOT NULL.

types functions

$types reads a field's resolved type ($field.mappedType). It is the same for every language.

FunctionContents
$types.typeOf($field)The short name of the language type. java.lang.Long → Long
$types.importOf($field)The full name for imports. Example: java.lang.Long
$types.simpleNameOf(fullType)A full name string turned into the short name
$types.categoryOf($field)The category. object when there is no resolved type
$types.isCategory($field, category)Whether it is in that category
$types.isDate, isNumber, isBoolean, isText, isArrayWhether it is in the datetime, number, boolean, text or array category. The argument is $field
$types.isDateOnly($field)Whether it is a date without time (M_LOCALDATE)
$types.isLongText($field)Whether it is M_CLOB or M_BLOB, or an M_STRING with a length of 1000 or more

Language-specific functions

FunctionContents
$java.imports()The import list collected from the entity's field types, excluding java.lang.*, without duplicates, sorted
$java.simpleName(fullType)A full name turned into the short name
$ts.propertyType($field)The TypeScript type. Always Date for the datetime category, otherwise the resolved type, or any if there is none
$ts.interfaceName(value)To PascalCase. user_profile → UserProfile
$py.snakeCase(value)To snake_case. UserProfile → user_profile
$py.typeHint($field)The Python type hint. Depending on the intermediate type: str, int, float, bool, datetime.date, datetime.time, datetime.datetime, list, otherwise Any

Date tool

$date is the DateTool from Velocity Tools. For example, $date.get('yyyy-MM-dd') writes the date the code was generated. Calls that return internal JDK objects, such as $date.timeZone, hit the restrictions in "Things to keep in mind" below and give no value.

Using values in install paths

A template's Installation Path field and Alternative path when file exists field are rendered with the same values and functions as the body. The alternative path is rendered only for file-writing templates with overwrite turned off.

src/main/java/$codegen.toPath($env.package.core, $entity.subPackage)/${entity.name}.java

Things to keep in mind

Template bodies are treated as untrusted input, because packs made by others and downloaded from the Store are rendered on your PC (desktop) or on the NeoSQL server (web). Templates can therefore use only the values and helper functions in the tables above and the methods of strings, lists and maps. They cannot do the following.

What is blockedExampleResult
Reflection and class loading$x.getClass().forName(…), $x.class.classLoader, $x.class.getMethods()No value. Written as $! it gives empty text, written as $ the notation is printed as is. On a class object, only $x.class.name can be read
Calling static methods through a class object$s.class.valueOf(5)No value
Files, network, processes, DB connections, system propertiesjava.io, java.nio, java.net, java.sql, Runtime, System, Thread and so onNo value
Including other files#include('…'), #parse('…')Rendering that template fails
  • A template whose rendering fails shows the error and the template name in the preview of the code generation window. The other templates are generated as usual.
  • To share common parts across templates, use the pack's variables ($env, entity and field variables) or put a #macro in each template instead of #include.
  • A reference with no value is not an error: it stays in the output as text such as $entity.nmae. To catch typos, read the generated result in the preview.
  • Template packs: where you define template bodies, install paths, variables and type mappings.
  • Generating source code: where you fill in variable values, generate code from tables, preview it and install it.
  • Template store: where you find and download published packs.
  • MCP tools: the generate-code tool, with which an external AI generates code from the same templates.