Hibernate Tips ‘n’ Tricks
Schnelle Lösungen für typische
Probleme und Anwendungsfälle
www.thoughts-on-java.org
www.thoughts-on-java.org
CDI 2.0 Expert
Group Member
Independent
author and
trainer
www.thoughts-on-java.org
@thjanssen123
/c/ThoughtsOnJava
/ThoughtsOnJava
HibernateTips
More than 70 solutions to common
Hibernate problems
www.hibernate-tips.com
ThorbenJanssen
Log Query Execution Time
www.thoughts-on-java.org
HibernateStatistics • Hibernate Statistics
• Collects internal information
• hibernate.generate_statistics = true
• Logging
• org.hibernate.stat = DEBUG
www.thoughts-on-java.org
Pagination
www.thoughts-on-java.org
Pagination • Defined on Query interface
www.thoughts-on-java.org
List<Author> authors = em.createQuery(“SELECT …”)
.setMaxResults(5)
.setFirstResult(0)
.getResultList();
Join Unassociated Entities
www.thoughts-on-java.org
Join • Hibernate-specific
• SQL-like syntax
www.thoughts-on-java.org
em.createQuery("SELECT b.title, count(r.id) "
+ "FROM Book b “
+ "INNER JOIN Review r ON r.fkBook = b.id GROUP BY b.title");
Map an SQL Snippet
www.thoughts-on-java.org
@Formula • Maps SQL snippet to entity attribute
• Read-only
• Native SQL
www.thoughts-on-java.org
@Formula(value = "date_part('year', age(dateOfBirth))")
private int age;
Map a Read-Only View
www.thoughts-on-java.org
@Immutable • View gets mapped like a table
• @Immutable
• Hibernate ignores all changes
www.thoughts-on-java.org
@Entity
@Immutable
public class BookView { … }
Order an Association
www.thoughts-on-java.org
@OrderBy • Adds ORDER BY clause to query
• Executed every time Hibernate fetches association
www.thoughts-on-java.org
@ManyToMany(mappedBy = "authors")
@OrderBy("title ASC")
private List<Book> books = new ArrayList<Book>();
Sort an Association
www.thoughts-on-java.org
@SortNatural • In Memory
• Uses Comparable implementation
www.thoughts-on-java.org
@ManyToMany(mappedBy = "authors")
@SortNatural
private SortedSet<Book> books = new TreeSet<Book>();
@SortComparator • Uses custom Comparator implementation
www.thoughts-on-java.org
@ManyToMany(mappedBy = "authors")
@SortComparator(SortById.class)
private SortedSet<Book> books = new TreeSet<Book>();
UUIDs as Primary Keys
www.thoughts-on-java.org
UUIDVersion4 • Random number-based UUID
• Default for java.util.UUID
www.thoughts-on-java.org
@Id
@GeneratedValue
@Column(name = "id", updatable = false, nullable = false)
private UUID id;
UUIDVersion1 • Based on IP and timestamp
www.thoughts-on-java.org
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator( name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator",
parameters = {
@Parameter(
name = "uuid_gen_strategy_class",
value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
)
}
)
private UUID id;
Map an Optional<T>
www.thoughts-on-java.org
Optional<T> • Not supported as attribute type
• Not serializable
• Override getter
www.thoughts-on-java.org
public Optional<Publisher> getPublisher() {
return Optional.ofNullable(this.publisher);
}
Map a LocalDate
www.thoughts-on-java.org
LocalDate • Supported as basic type
• Hibernate 5 and JPA 2.2
www.thoughts-on-java.org
@Entity
public class Book {
private LocalDate publishingDate;
…
}
Custom Data Types
www.thoughts-on-java.org
AttributeConverte
r• Implement custom conversion
www.thoughts-on-java.org
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate attribute) { … }
@Override
public LocalDate convertToEntityAttribute(Date dbData) { ... }
}
Multi-Tenancy
www.thoughts-on-java.org
SeparateDB
www.thoughts-on-java.org
Application
DB
Tenant 1
DB
Tenant 2
Tenant 1
Tenant 2
SeparateSchema
www.thoughts-on-java.org
Application
Tenant 1
Tenant 2
Schema Tenant 1
Schema Tenant 2
Implementation • Implement 2 interfaces
• MultiTenantConnectionProvider
• Extent AbstractMultiTenantConnectionProvider
• CurrentTenantIdentifierResolver
www.thoughts-on-java.org
Auditing
www.thoughts-on-java.org
Envers • Add Hibernate Envers to your project
• Activate auditing
www.thoughts-on-java.org
@Entity
@Audited
public class Book { … }
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.2.10</version>
</dependency>
www.thoughts-on-java.org
Hibernate Tips
More than 70 solutions to common
common Hibernate problems
www.hibernate-tips.com

Hibernate Tips ‘n’ Tricks - 15 Tips to solve common problems