View entity is a class that maps to a database view. You can create a view entity by defining a new class and mark it with @ViewEntity():
@ViewEntity() accepts following options:
name - view name. If not specified, then view name is generated from entity class name.
database - database name in selected DB server.
schema - schema name.
expression - view definition. Required parameter.
expression can be string with properly escaped columns and tables, depend on database used (postgres in example):
@ViewEntity({expression:` SELECT "post"."id" "id", "post"."name" AS "name", "category"."name" AS "categoryName" FROM "post" "post" LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"`})
Note: parameter binding is not supported due to drivers limitations. Use the literal parameters instead.
Each view entity must be registered in your connection options:
Or you can specify the whole directory with all entities inside - and all of them will be loaded:
View Entity columns
To map data from view into the correct entity columns you must mark entity columns with @ViewColumn() decorator and specify these columns as select statement aliases.
example with string expression definition:
example using QueryBuilder:
Complete example
Let create two entities and a view containing aggregated data from these entities:
then fill these tables with data and request all data from PostCategory view: