Hibernate Decorator

Kotlin library to wrap around hibernate and make database access simpler

2020.06.09 2020.12.06

Project archived on 09 December 2020


This project served more as a way to get to know hibernate and play around with it more than anything else.

While I did initially have the idea of using it as a library in other projects, that didn't really go anywhere because of all the complexity around Hibernate and the requirement to maintain more code myself. It just didn't make sense to use this library instead of either plain Hibernate, or a more established framework such as Spring.

That all being said, it was still a great way to learn about Hibernate and library design in general.


features

Wraps around Hibernate instead of replacing it

This means that you can get all the benefits this library provides without losing all the stuff Hibernate gives you. You can always access the underlying Hibernate classes and data.

Database entities and repositories

The library includes some base entity interfaces and classes to extend that include standard data (e.g. entity ID) as well as repository classes to save and fetch data.

Query support

One of the most fun things to implement was support for queries.

The goal was to define the necessary classes and methods to build queries that would be type-safe at build-time. These query objects would then get converted to JPQL commands to be executed by Hibernate.

It was still limited when I made the decision to archive the project, really only having support for base where clauses, but the plan was to support all kinds of complex queries and sorting.

Below is an example of what the query syntax looks like. This example builds a new database connection, creates a new session for that connection, and queries the database for all matching entities.

HibernateDecoratorApi.newDbApiBuilder().build().use { api ->
    api.newSession().use { session ->
        val repo = session.newRepository(MockDbEntity::class.java)

        // Build query
        val query = repo.newQuery()
        query.where("id", 15)
        query.where("field1", 30)
        query.where("field2", 45)
        query.where("field3", 60)

        // Get all matching entities
        val result = query.all()
    }
}