Dynamic Mapping with Hibernate – 使用Hibernate的动态映射

最后修改: 2017年 10月 30日

1. Introduction


In this article, we’ll explore some dynamic mapping capabilities of Hibernate with the @Formula, @Where, @Filter and @Any annotations.


Note that although Hibernate implements the JPA specification, annotations described here are available only in Hibernate and are not directly portable to other JPA implementations.


2. Project Setup


To demonstrate the features, we’ll only need the hibernate-core library and a backing H2 database:



For the current version of the hibernate-core library, head over to Maven Central.

关于当前版本的hibernate-core库,请访问Maven Central

3. Calculated Columns With @Formula


Suppose we want to calculate an entity field value based on some other properties. One way to do it would be by defining a calculated read-only field in our Java entity:


public class Employee implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private long grossIncome;

    private int taxInPercents;

    public long getTaxJavaWay() {
        return grossIncome * taxInPercents / 100;


The obvious drawback is that we’d have to do the recalculation each time we access this virtual field by the getter.


It would be much easier to get the already calculated value from the database. This can be done with the @Formula annotation:


public class Employee implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private long grossIncome;

    private int taxInPercents;

    @Formula("grossIncome * taxInPercents / 100")
    private long tax;


With @Formula, we can use subqueries, call native database functions and stored procedures and basically do anything that does not break the syntax of an SQL select clause for this field.


Hibernate is smart enough to parse the SQL we provided and insert correct table and field aliases. The caveat to be aware of is that since the value of the annotation is raw SQL, it may make our mapping database-dependent.


Also, keep in mind that the value is calculated when the entity is fetched from the database. Hence, when we persist or update the entity, the value would not be recalculated until the entity is evicted from the context and loaded again:


Employee employee = new Employee(10_000L, 25);


employee = session.get(Employee.class, employee.getId());

4. Filtering Entities With @Where


Suppose we want to provide an additional condition to the query whenever we request some entity.


For instance, we need to implement “soft delete”. This means that the entity is never deleted from the database, but only marked as deleted with a boolean field.

例如,我们需要实现 “软删除”。这意味着实体永远不会从数据库中删除,而只是用一个boolean字段标记为删除。

We’d have to take great care with all existing and future queries in the application. We’d have to provide this additional condition to every query. Fortunately, Hibernate provides a way to do this in one place:


@Where(clause = "deleted = false")
public class Employee implements Serializable {

    // ...

The @Where annotation on a method contains an SQL clause that will be added to any query or subquery to this entity:




employee = session.find(Employee.class, employee.getId());

As in the case of @Formula annotation, since we’re dealing with raw SQL, the @Where condition won’t be reevaluated until we flush the entity to the database and evict it from the context.


Until that time, the entity will stay in the context and will be accessible with queries and lookups by id.


The @Where annotation can also be used for a collection field. Suppose we have a list of deletable phones:


public class Phone implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private boolean deleted;

    private String number;


Then, from the Employee side, we could map a collection of deletable phones as follows:


public class Employee implements Serializable {
    // ...

    @JoinColumn(name = "employee_id")
    @Where(clause = "deleted = false")
    private Set<Phone> phones = new HashSet<>(0);


The difference is that the Employee.phones collection would always be filtered, but we still could get all phones, including deleted ones, via direct query:

不同的是,Employee. phones集合将总是被过滤的,但我们仍然可以通过直接查询获得所有的电话,包括已删除的电话。


employee = session.find(Employee.class, employee.getId());

List<Phone> fullPhoneList 
  = session.createQuery("from Phone").getResultList();

5. Parameterized Filtering With @Filter


The problem with @Where annotation is that it allows us to only specify a static query without parameters, and it can’t be disabled or enabled by demand.


The @Filter annotation works the same way as @Where, but it also can be enabled or disabled on session level, and also parameterized.


5.1. Defining the @Filter


To demonstrate how @Filter works, let’s first add the following filter definition to the Employee entity:


    name = "incomeLevelFilter", 
    parameters = @ParamDef(name = "incomeLimit", type = "int")
    name = "incomeLevelFilter", 
    condition = "grossIncome > :incomeLimit"
public class Employee implements Serializable {

The @FilterDef annotation defines the filter name and a set of its parameters that will participate in the query. The type of the parameter is the name of one of the Hibernate types (Type, UserType or CompositeUserType), in our case, an int.


The @FilterDef annotation may be placed either on the type or on package level. Note that it does not specify the filter condition itself (although we could specify the defaultCondition parameter).

@FilterDef 注解可以放在类型上,也可以放在包层上。请注意,它并不指定过滤条件本身(尽管我们可以指定defaultCondition参数)。

This means that we can define the filter (its name and set of parameters) in one place and then define the conditions for the filter in multiple other places differently.


This can be done with the @Filter annotation. In our case, we put it in the same class for simplicity. The syntax of the condition is a raw SQL with parameter names preceded by colons.


5.2. Accessing Filtered Entities


Another difference of @Filter from @Where is that @Filter is not enabled by default. We have to enable it on the session level manually, and provide the parameter values for it:


  .setParameter("incomeLimit", 11_000);

Now suppose we have the following three employees in the database:


session.save(new Employee(10_000, 25));
session.save(new Employee(12_000, 25));
session.save(new Employee(15_000, 25));

Then with the filter enabled, as shown above, only two of them will be visible by querying:


List<Employee> employees = session.createQuery("from Employee")

Note that both the enabled filter and its parameter values are applied only inside the current session. In a new session without filter enabled, we’ll see all three employees:


session = HibernateUtil.getSessionFactory().openSession();
employees = session.createQuery("from Employee").getResultList();

Also, when directly fetching the entity by id, the filter is not applied:


Employee employee = session.get(Employee.class, 1);

5.3. @Filter and Second-Level Caching


If we have a high-load application, then we’d definitely want to enable Hibernate second-level cache, which can be a huge performance benefit. We should keep in mind that the @Filter annotation does not play nicely with caching.


The second-level cache only keeps full unfiltered collections. If it wasn’t the case, then we could read a collection in one session with filter enabled, and then get the same cached filtered collection in another session even with filter disabled.


This is why the @Filter annotation basically disables caching for the entity.


6. Mapping Any Entity Reference With @Any


Sometimes we want to map a reference to any of multiple entity types, even if they are not based on a single @MappedSuperclass. They could even be mapped to different unrelated tables. We can achieve this with the @Any annotation.


In our example, we’ll need to attach some description to every entity in our persistence unit, namely, Employee and Phone. It’d be unreasonable to inherit all entities from a single abstract superclass just to do this.


6.1. Mapping Relation With @Any


Here’s how we can define a reference to any entity that implements Serializable (i.e., to any entity at all):


public class EntityDescription implements Serializable {

    private String description;

        metaDef = "EntityDescriptionMetaDef",
        metaColumn = @Column(name = "entity_type"))
    @JoinColumn(name = "entity_id")
    private Serializable entity;


The metaDef property is the name of the definition, and metaColumn is the name of the column that will be used to distinguish the entity type (not unlike the discriminator column in the single table hierarchy mapping).


We also specify the column that will reference the id of the entity. It’s worth noting that this column will not be a foreign key because it can reference any table that we want.


The entity_id column also can’t generally be unique because different tables could have repeated identifiers.


The entity_type/entity_id pair, however, should be unique, as it uniquely describes the entity that we’re referring to.


6.2. Defining the @Any Mapping With @AnyMetaDef


Right now, Hibernate does not know how to distinguish different entity types, because we did not specify what the entity_type column could contain.


To make this work, we need to add the meta-definition of the mapping with the @AnyMetaDef annotation. The best place to put it would be the package level, so we could reuse it in other mappings.


Here’s how the package-info.java file with the @AnyMetaDef annotation would look like:


    name = "EntityDescriptionMetaDef", 
    metaType = "string", 
    idType = "int",
    metaValues = {
        @MetaValue(value = "Employee", targetEntity = Employee.class),
        @MetaValue(value = "Phone", targetEntity = Phone.class)
package com.baeldung.hibernate.pojo;

Here we’ve specified the type of the entity_type column (string), the type of the entity_id column (int), the acceptable values in the entity_type column (“Employee” and “Phone”) and the corresponding entity types.


Now, suppose we have an employee with two phones described like this:


Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");

Now we could add descriptive metadata to all three entities, even though they have different unrelated types:


EntityDescription employeeDescription = new EntityDescription(
  "Send to conference next year", employee);
EntityDescription phone1Description = new EntityDescription(
  "Home phone (do not call after 10PM)", phone1);
EntityDescription phone2Description = new EntityDescription(
  "Work phone", phone1);

7. Conclusion


In this article, we’ve explored some of Hibernate’s annotations that allow fine-tuning entity mapping using raw SQL.


The source code for the article is available over on GitHub.