A beginner’s guide to Hibernate Types

The basic mapping concepts

When learning Hibernate, many like to jump to ParentChild associations without mastering the object relation mapping basics. It’s very important to understand the basic mapping rules for individual Entities before starting modelling Entity associations.

Hibernate types

A Hibernate type is a bridge between an SQL type and a Java primitive/Object type.

These are the types Hibernate supports by default:

Hibernate type (org.hibernate.type) JDBC type Java type
StringType VARCHAR String
MaterializedClob CLOB String
TextType LONGVARCHAR String
CharacterType CHAR char or Character
BooleanType BIT boolean or Boolean
NumericBooleanType INTEGER (e.g. 0 = false and 1 = true) boolean or Boolean
YesNoType CHAR (e.g. ‘N’ or ‘n’ = false and ‘Y’ or ‘y’ = true) boolean or Boolean
TrueFalseType CHAR (e.g. ‘F’ or ‘f’ = false and ‘T’ or ‘t’ = true) boolean or Boolean
ByteType TINYINT byte or Byte
ShortType SMALLINT short or Short
IntegerType INTEGER int or Integer
LongType BIGINT long or Long
FloatType FLOAT float or Float
DoubleType DOUBLE double or Double
BigIntegerType NUMERIC BigInteger
BigDecimalType NUMERIC BigDecimal
TimestampType TIMESTAMP java.sql.Timestamp or java.util.Date
TimeType TIME java.sql.Time
DateType DATE java.sql.Date
CalendarType TIMESTAMP java.util.Calendar or java.util.GregorianCalendar
CalendarType DATE java.util.Calendar or java.util.GregorianCalendar
CurrencyType VARCHAR java.util.Currency
LocaleType VARCHAR java.util.Locale
TimeZoneType VARCHAR java.util.TimeZone
UrlType VARCHAR java.net.URL
ClassType VARCHAR java.lang.Class
BlobType BLOB java.sql.Blob
ClobType CLOB java.sql.Clob
BinaryType VARBINARY byte[] or Byte[]
BinaryType BLOB byte[] or Byte[]
BinaryType LONGVARBINARY byte[] or Byte[]
BinaryType LONGVARBINARY byte[] or Byte[]
CharArrayType VARCHAR char[] or Character[]
UUIDBinaryType BINARY java.util.UUID
UUIDBinaryType CHAR or VARCHAR java.util.UUID
UUIDBinaryType PostgreSQL UUID java.util.UUID
SerializableType VARBINARY Serializable

You can always define your own custom types as we will see in a future article.

Embedded (a.k.a Component) Types

You can group multiple columns to a specific Java type that can be reused throughout your domain model. If the mapped Java object is always dependent on some external Entity you can choose an Embeddable type for such domain model mapping.

An Embeddable object may contain both basic types and association mappings but it can never contain an @Id. The Embeddable object is persisted/removed along with its owning entity.

Assuming we have the following SQL table:

CREATE TABLE entity_event
  (
     id           BIGINT GENERATED BY DEFAULT 
                  AS IDENTITY (START WITH 1),
     entity_class VARCHAR(255),
     entity_id    BIGINT,
     message      VARCHAR(255),
     PRIMARY KEY (id)
  );  

We could group the entity_class and entity_id to an Embeddable object that we’ll employ in two different owning Entities.

The Embeddable object looks like this:

@Embeddable
public class EntityIdentifier 
    implements Serializable {

    @Column(name = "entity_id", 
         nullable = true)
    private Long entityId;

    @Column(name = "entity_class", 
         nullable = true)
    private Class entityClass;

    public EntityIdentifier() {
    }

    public EntityIdentifier(Class entityClass, 
        Long entityId) {
        this.entityClass = entityClass;
        this.entityId = entityId;
    }

    public Class getEntityClass() { 
        return entityClass; 
    }

    public void setEntityClass(Class entityClass) { 
        this.entityClass = entityClass; 
    }

    public Long getEntityId() { 
        return entityId; 
    }

    public void setEntityId(Long entityId) { 
        this.entityId = entityId; 
    }
}

The associated Entity table will inherit the Embeddable properties associated columns.

Entity

An Entity is the Java equivalent of an SQL table row. The entity must contain an @Id property mapping the associated table Primary Key.

The application logic makes changes to Entities properties and notifies the Persistence Context of Entity state changes (persist, merge, remove). The persistence context will therefore translate all Entity changes to SQL statements.

Assuming we have the following SQL tables:

CREATE TABLE entity_attribute
  (
     id           BIGINT GENERATED BY DEFAULT 
                  AS IDENTITY (START WITH 1),
     entity_class VARCHAR(255),
     entity_id    BIGINT,
     name         VARCHAR(255),
     VALUE        VARCHAR(255),
     PRIMARY KEY (id)
  );
 CREATE TABLE entity_event
  (
     id           BIGINT GENERATED BY DEFAULT 
                  AS IDENTITY (START WITH 1),
     entity_class VARCHAR(255),
     entity_id    BIGINT,
     message      VARCHAR(255),
     PRIMARY KEY (id)
  );    

We can make use of the EntityIdentifier Embeddable type since both tables contain the entity_class and entity_id columns.

@Entity
@Table(name = "entity_attribute")
public class EntityAttribute {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private String value;

    private EntityIdentifier entityIdentifier;

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public EntityIdentifier getEntityIdentifier() {
        return entityIdentifier;
    }

    public void setEntityIdentifier(
        EntityIdentifier entityIdentifier) {
        this.entityIdentifier = entityIdentifier;
    }
}

@Entity
@Table(name = "entity_event")
public class EntityEvent {

    @Id
    @GeneratedValue
    private Long id;

    private String message;

    private EntityIdentifier entityIdentifier;

    public Long getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public EntityIdentifier getEntityIdentifier() {
        return entityIdentifier;
    }

    public void setEntityIdentifier(
        EntityIdentifier entityIdentifier) {
        this.entityIdentifier = entityIdentifier;
    }
}

Testing time

We will create one EntityEvent and one EntityAttribute for a given Product to see how the Embeddable is being persisted along with the owning entities:

@Test
public void testEntityIdentifier() {
    doInTransaction(session -> {
        Product product = new Product("LCD");
        session.persist(product);
        EntityEvent productEvent = new EntityEvent();
        productEvent.setMessage(String.format(
            "Product %s added", product.getName()));
        productEvent.setEntityIdentifier(
            new EntityIdentifier(
                product.getClass(),
                product.getId()
        ));
        session.persist(productEvent);
        EntityAttribute productAttribute = 
            new EntityAttribute();
        productAttribute.setName("AD_CAMPAIGN");
        productAttribute.setValue("LCD_Sales");
        productAttribute.setEntityIdentifier(
            new EntityIdentifier(
                product.getClass(),
                product.getId()
        ));
        session.persist(productAttribute);
        assertSame(1, session.createQuery(
            "select ea " +
            "from EntityAttribute ea " +
            "where " +
            "   ea.entityIdentifier = :entityIdentifier")
            .setParameter("entityIdentifier",
                new EntityIdentifier(
                    product.getClass(), product.getId()))
            .list().size());
        return null;
    });
}

Running this test generates the following SQL output:

INSERT INTO product (
    id, 
    name
)
VALUES (
    DEFAULT, 
    'LCD'
);

INSERT INTO entity_event (
	id,
	entity_class,
	entity_id,
	message
)
VALUES (
	DEFAULT,
	'com.vladmihalcea.hibernate.masterclass.laboratory.entityidentifier.Product',
	1,
	'Product LCD added'
);

INSERT INTO entity_attribute (
	id,
	entity_class,
	entity_id,
	name,
	VALUE
)
VALUES (
	DEFAULT,
	'com.vladmihalcea.hibernate.masterclass.laboratory.entityidentifier.Product',
	1,
	'AD_CAMPAIGN',
	'LCD_Sales'
);

SELECT entityattr0_.id           AS id1_0_,
       entityattr0_.entity_class AS entity_c2_0_,
       entityattr0_.entity_id    AS entity_i3_0_,
       entityattr0_.name         AS name4_0_,
       entityattr0_.VALUE        AS value5_0_
FROM   entity_attribute entityattr0_
WHERE  entityattr0_.entity_class = 'com.vladmihalcea.hibernate.masterclass.laboratory.entityidentifier.Product'
       AND entityattr0_.entity_id = 1;

If you enjoyed this article, I bet you are going to love my book as well.

Conclusion

There are still many concepts we need to cover before getting to understand Entity associations. You should always take you time to understand the basic concepts before jumping to more advanced topics. My next post will be about Entity Identifiers and all the available generator techniques.

Code available on GitHub.

Enter your email address to follow this blog and receive notifications of new posts by email.

Advertisements

9 thoughts on “A beginner’s guide to Hibernate Types

  1. Hi,
    What is your method ‘doInTransaction’? Are you using Spring? Whould you pls. tell what your Spring configuration is and how you set it up?
    Thank you,
    Alla

    1. Hi. It’s not decided and it’s probably going to be rejected since it uses proprietary CTE syntax. If MySQL 8 is going to add support for CTE, then it will be easier to integrate it.

      1. Hi, I understand that CTE syntax is restricted to Postgres. On a sidenote, are you aware of similar project, where Oracle is supported, in the sense that temporary table creation is avoided in case of Oracle database. Basically, the issue which I am facing is that user does not have permission to create temporary tables and we are in a situation that we cannot give permission to that user to create temporary tables.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s