How to emulate @CreatedBy and @LastModifiedBy from Spring Data using the @GeneratorType Hibernate annotation

Introduction

Hibernate comes with many additions to the standard JPA specification. One such example is the @GeneratorType annotation which allows you to customize the way a given entity property value is automatically generated.

If you’re using Spring Data, you can simply use the @CreatedBy and @LastModifiedBy annotations and the annotated entity properties are going to be populated with the currently logged user.

If you’re not using Spring Data, then you can easily emulate the same behavior using the Hibernate-specific @GeneratorType annotation and the ValueGenerator callback mechanism.

Continue reading “How to emulate @CreatedBy and @LastModifiedBy from Spring Data using the @GeneratorType Hibernate annotation”

Advertisements

How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate

Introduction

Last week, one of my blog readers asked me of a way to reuse the @Id mapping so that it won’t have to be declared on each an every entity.

Because this is a good opportunity to introduce @MappedSuperclass, I decided to answer the question with a blog post.

Continue reading “How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate”

How do UPSERT and MERGE work in Oracle, SQL Server, PostgreSQL and MySQL

Introduction

Last week, Burkhard Graves asked me to answer the following StackOverflow question:

And, since he wasn’t convinced about my answer:

I decided to turn it into a dedicated article and explain how UPSERT and MERGE work in the top 4 most common relational database systems: Oracle, SQL Server, PostgreSQL, and MySQL.

Continue reading “How do UPSERT and MERGE work in Oracle, SQL Server, PostgreSQL and MySQL”

The best way to map a @NaturalId business key with JPA and Hibernate

Introduction

As I explained in this free chapter of my book, Hibernate offers many benefits over standard JPA. One such example is the @NaturalId mapping.

In this article, you are going to see what is the best way to map a natural business key when using Hibernate.

Continue reading “The best way to map a @NaturalId business key with JPA and Hibernate”

How does Hibernate handle JPA Criteria API literals

Introduction

The JPA specification is like a Java interface, However, when it comes to performance, implementation details matter a lot. That’s why, even if you use the JPA standard, you still need to know how the underlying provider implements the standard specification.

For instance, if we take this tweet from Gareth Western:

We can clearly see that there is an issue in the way literals might be handled by Hibernate when executing a Criteria API query.

Therefore, in this article, we are going to see how literals are handled by Hibernate and explain what we have changed in Hibernate 5.2.12.

Continue reading “How does Hibernate handle JPA Criteria API literals”