Setting up JPA with Hibernate as a provider in IntelliJ

Coding in the original Hibernate style using SessionFactory and Session with a static utility method to set up the SessionFactory depends on Hibernate core but using JPA with Hibernate as the datasource provider has an additional dependency on the Hibernate entity manager package. Specifying JPA with Hibernate as provider does NOT add this package to your lib folder – you will need to go and get it from maven central (and add it to any build artefacts).

If your using a Maven project then the dependencies are:

Once you have added the required dependencies then create the directory META-INF in /main/java/resources and create the file persistence.xml in that directory.

I’m using derby for the example but swap the dependency above for the driver for your database of choice. The persistence.xml file holds the details of the connection used by the entity manager and is referenced by the name of the persistence unit (DbConf in the example below).

Not the use of “create” as the value for hbm2ddl – this create the database tables on each run. Alternative settings include validate and update.

It’s also worth setting up some logging. I’ve added log4j (not log4j 2) into the dependencies and to configure the logging add a file to the resources folder. In the example below I’ve left the logging to trace.

Using the ORM is then a simple matter of creating an entity manager from the persistence.xml properties and specifying the domain class using the appropriate annotations.

My domain class meets the minimum requirements for a persistent class. It is annotated with @Entity, has a field specified as @Id and has a no arg constructor.

At this point running the main method should insert a table and record into a derby database (assuming derby is running – download and set up from

Leave a Reply

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