View
We use @View on an entity bean to indicate that it is based on a
database view rather than a table.
@Entity
@View(name = "order_vw", dependentTables = {"o_order", "o_order_detail"})
public class MyOrderView {
// fields, accessors etc
}
Note that we do not need to map a @Id property (actually we don't
need to map one for a normal entity either).
Attributes
- name - the name of the database view this entity bean is based on.
- dependentTables - the tables the view is dependent on, used to invalidate L2 caching (see below). Optional and defaults to none.
Dependent Tables
If we enable L2 caching on the entity that is based on a view then we should
specify via dependentTables the underlying tables that the view
uses. When data for these tables is modified that will automatically invalidate
the L2 cache for that view.
DDL and migration generation
Entities mapped with @View are excluded from Ebean's automatic DDL and
migration generation - Ebean will not generate a create table statement
or a migration for it. We need to supply the DDL that creates the view ourselves
via extra-ddl.xml (see below).
Extra DDL to define the view
For ebean to execute DDL to create the database view we need to additionally have a
extra-ddl.xml. Refer to docs / extra-ddl
for more details.
The DDL in extra-ddl.xml is run after the create-all DDL
during normal testing, and copied as "repeatable" migrations that FlywayDb (or
Ebean's own migration runner) will (re)run whenever the script content changes.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<extra-ddl xmlns="http://ebean-orm.github.io/xml/ns/extraddl">
<ddl-script name="order views" platforms="h2" drop="true">
drop view order_agg_vw if exists;
</ddl-script>
<ddl-script name="order views" platforms="postgres,oracle">
create or replace view order_agg_vw as
select d.order_id, sum(d.order_qty * d.unit_price) as order_total,
sum(d.ship_qty * d.unit_price) as ship_total
from o_order_detail d
group by d.order_id
</ddl-script>
</extra-ddl>