A beginner’s guide to Hibernate Types

Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn’t that be just awesome?

Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.

So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night!

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;

I'm running an online workshop on the 20-21 and 23-24 of November about High-Performance Java Persistence.

If you enjoyed this article, I bet you are going to love my Book and Video Courses 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.

Transactions and Concurrency Control eBook

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.