How do find and getReference EntityManager methods work when using JPA and Hibernate

Introduction

While doing my High-Performance Java Persistence training, I realized that not all developers are familiar with the getReference method of the JPA EntityManager and most of them use find almost exclusively.

In this article, we are going to see the difference between the find and getReference method so that it’s clear when to apply them depending on the underlying use case.

Continue reading “How do find and getReference EntityManager methods work when using JPA and Hibernate”

MariaDB 10.3 supports database sequences

Introduction

Traditionally, both MySQL and MariaDB relied on AUTO_INCREMENT columns to generate an IDENTITY Primary Key. Although IDENTITY columns are very efficient in generating the Primary Key value, when it comes to using JPA and Hibernate, the IDENTITY generator prevents us from using JDBC batch inserts.

To automatically enroll multiple INSERT, UPDATE or DELETE statements, Hibernate requires delaying the SQL statement until the Persistence Context is flushed. This works very well for the SEQUENCE identifier since the entity identifier can be fetched prior to executing the INSERT statement.

However, for IDENTITY columns, the only way to know the entity identifier is if we execute the SQL INSERT statement. And, Hibernate needs the entity identifier when persisting an entity because otherwise, it cannot build the key which is used for locating an entity in the currently running Persistence Context.

Continue reading “MariaDB 10.3 supports database sequences”

How to synchronize bidirectional entity associations with JPA and Hibernate

Introduction

While answering this StackOverflow question, I realized that it’s a good idea to summarize how various bidirectional associations should be synchronized when using JPA and Hibernate.

Therefore, in this article, you are going to learn how and also why you should always synchronize both sides of an entity relationship, no matter if it’s @OneToMany, @OneToOne or @ManyToMany.

Continue reading “How to synchronize bidirectional entity associations with JPA and Hibernate”

How to use @PrePersist and @PreUpdate on Embeddable with JPA and Hibernate

Introduction

In a previous article, I explained how you could audit entity modifications using the JPA @EntityListeners for embeddable types.

Since Hibernate ORM 5.2.17 now allows you to use the @PrePersist and @PreUpdate JPA entity listeners, we can simplify the previous example, as you will see in this article.

Continue reading “How to use @PrePersist and @PreUpdate on Embeddable with JPA and Hibernate”