Mapping types
Hibernate understands both the Java and JDBC representations of application data.
The ability to read/write this data from/to the database is the function of a Hibernate type.
A type, in this usage, is an implementation of the org.hibernate.type.Type
interface.
This Hibernate type also describes various aspects of behavior of the Java type such as how to check for equality, how to clone values, etc.
Usage of the word type
The Hibernate type is neither a Java type nor a SQL data type. It provides information about both of these as well as understanding marshalling between. When you encounter the term type in discussions of Hibernate, it may refer to the Java type, the JDBC type, or the Hibernate type, depending on context. |
To help understand the type categorizations, let’s look at a simple table and domain model that we wish to map.
create table Contact (
id integer not null,
first varchar(255),
last varchar(255),
middle varchar(255),
notes varchar(255),
starred boolean not null,
website varchar(255),
primary key (id)
)
@Entity(name = "Contact")
public static class Contact {
@Id
private Integer id;
private Name name;
private String notes;
private URL website;
private boolean starred;
//Getters and setters are omitted for brevity
}
@Embeddable
public class Name {
private String first;
private String middle;
private String last;
// getters and setters omitted
}
In the broadest sense, Hibernate categorizes types into two groups:
Value types
A value type is a piece of data that does not define its own lifecycle. It is, in effect, owned by an entity, which defines its lifecycle.
Looked at another way, all the state of an entity is made up entirely of value types.
These state fields or JavaBean properties are termed persistent attributes.
The persistent attributes of the Contact
class are value types.
Value types are further classified into three sub-categories:
- Basic types
-
in mapping the
Contact
table, all attributes except for name would be basic types. Basic types are discussed in detail in Basic Types - Embeddable types
-
the name attribute is an example of an embeddable type, which is discussed in details in Embeddable Types
- Collection types
-
although not featured in the aforementioned example, collection types are also a distinct category among value types. Collection types are further discussed in Collections
Entity types
Entities, by nature of their unique identifier, exist independently of other objects whereas values do not.
Entities are domain model classes which correlate to rows in a database table, using a unique identifier.
Because of the requirement for a unique identifier, entities exist independently and define their own lifecycle.
The Contact
class itself would be an example of an entity.
Mapping entities is discussed in detail in Entity.