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:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.7.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
For the current version of the hibernate-core library, head over to 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:
@Entity
public class Employee implements Serializable {
@Id
@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:
@Entity
public class Employee implements Serializable {
@Id
@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);
session.save(employee);
session.flush();
session.clear();
employee = session.get(Employee.class, employee.getId());
assertThat(employee.getTax()).isEqualTo(2_500L);
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.
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:
@Entity
@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.setDeleted(true);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNull();
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:
@Entity
public class Phone implements Serializable {
@Id
@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 {
// ...
@OneToMany
@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.getPhones().iterator().next().setDeleted(true);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(1);
List<Phone> fullPhoneList
= session.createQuery("from Phone").getResultList();
assertThat(fullPhoneList).hasSize(2);
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:
@FilterDef(
name = "incomeLevelFilter",
parameters = @ParamDef(name = "incomeLimit", type = Integer.class)
)
@Filter(
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 Integer.
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).
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:
session.enableFilter("incomeLevelFilter")
.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")
.getResultList();
assertThat(employees).hasSize(2);
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();
assertThat(employees).hasSize(3);
Also, when directly fetching the entity by id, the filter is not applied:
Employee employee = session.get(Employee.class, 1);
assertThat(employee.getGrossIncome()).isEqualTo(10_000);
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):
@Entity
public class EntityDescription implements Serializable {
private String description;
@Any
@AnyDiscriminator(DiscriminatorType.STRING)
@AnyDiscriminatorValue(discriminator = "S", entity = Employee.class)
@AnyDiscriminatorValue(discriminator = "I", entity = Phone.class)
@AnyKeyJavaClass(Integer.class)
@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. Example of using Entity Descriptor
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.