The Wild

How to Create a Java-Based Hibernate Application

· 6 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Creating a Java-based Hibernate application means setting up a project that uses Hibernate ORM to map Java objects to database tables, then using a SessionFactory and sessions to persist and query data. The short version: add the Hibernate and JDBC driver dependencies, create an entity class with JPA annotations, configure hibernate.cfg.xml or a persistence.xml, build a SessionFactory, and run transactions through a Session. This guide walks through that process with Maven, a relational database, and a small working example.

What You'll Need

  • JDK 17 or later installed and JAVA_HOME set.
  • Maven 3.8+ (or Gradle, if you prefer; the steps below use Maven).
  • A relational database you can connect to, such as PostgreSQL, MySQL, or H2 for local testing.
  • The JDBC driver for that database.
  • An IDE such as IntelliJ IDEA, Eclipse, or VS Code with Java extensions.
  • Basic familiarity with Java classes, annotations, and SQL.

Step-by-Step

  1. Create a Maven project. Use your IDE's Maven wizard or run mvn archetype:generate and pick a simple archetype. Set a group ID like com.example and an artifact ID like hibernate-demo. Confirm the project builds with mvn compile before adding anything else.
  2. Add dependencies to pom.xml. Include Hibernate Core (the hibernate-core artifact), the JPA API if you plan to use persistence.xml, your database driver, and a logging backend such as SLF4J with a simple binding. Pin explicit versions rather than relying on ranges so builds stay reproducible. After editing, run mvn dependency:tree to confirm there are no conflicting Hibernate or JPA versions pulled in transitively.
  3. Create the database and a table. For example, in PostgreSQL: CREATE TABLE employee (id BIGSERIAL PRIMARY KEY, name VARCHAR(100), salary NUMERIC(10,2));. Hibernate can generate schema for you with hbm2ddl.auto, but creating the table yourself first makes it easier to see what Hibernate expects and avoids surprises later.
  4. Write the entity class. Annotate a plain Java class with @Entity, give it a no-argument constructor, and mark the primary key with @Id and @GeneratedValue. Map each field to a column with @Column where the names differ. Keep fields private and provide getters and setters. Example fields: Long id, String name, BigDecimal salary. Make the class Serializable if you plan to cache or transfer it.
  5. Configure Hibernate. Create src/main/resources/hibernate.cfg.xml (or a META-INF/persistence.xml if using JPA). Set the dialect (for example org.hibernate.dialect.PostgreSQLDialect), the JDBC URL, username, password, and driver class. Add <mapping class="com.example.Employee"/> so Hibernate knows about the entity. Set hibernate.show_sql to true during development so you can see the generated SQL. Never commit real credentials; use environment variables or a local properties file excluded from version control.
  6. Build a SessionFactory. In a small utility class, create a StandardServiceRegistry from the configuration, then a Metadata object, then a SessionFactory. Build it once and reuse it for the life of the application; creating a SessionFactory per request is expensive. Close it in a shutdown hook or finally block when the application stops.
  7. Persist and query data. Open a Session with sessionFactory.openSession(), begin a transaction with session.beginTransaction(), call session.persist(entity) or session.save(entity), then commit. For reads, use session.get(Employee.class, id) or a HQL query such as from Employee where salary > :min. Always close the session, ideally with try-with-resources.
  8. Handle transactions correctly. Wrap each unit of work in a transaction and roll back on exception. A common pattern is a try block that commits, a catch block that rolls back, and a finally block that closes the session. Do not leave transactions open across user think time or network calls.
  9. Test the flow. Write a small main method or a JUnit test that inserts one row, reads it back, updates a field, and deletes it. Check the SQL Hibernate logs to confirm the statements match your expectations. If the table is not found, revisit step 3 and the dialect setting.
  10. Package and run. Run mvn package and execute the resulting jar, or run from the IDE. Confirm the application connects with the same credentials in a clean environment, not just your machine.

Common Mistakes

  • Forgetting the no-argument constructor on an entity; Hibernate needs it to instantiate objects.
  • Mixing Hibernate versions with an incompatible JPA API jar, which produces confusing NoSuchMethodError or annotation errors.
  • Leaving hbm2ddl.auto set to create or create-drop in production, which can drop or recreate tables.
  • Using one SessionFactory per request instead of one per application.
  • Opening a session without a transaction and expecting writes to persist; Hibernate requires an active transaction for changes.
  • Storing database passwords in a committed configuration file.
  • Mapping a field named id without @Id, or forgetting @GeneratedValue and then inserting null keys.

Tips

  • Start with H2 in-memory for fast feedback, then switch to your real database once the mapping works.
  • Enable hibernate.format_sql alongside show_sql to make generated SQL readable.
  • Prefer JPA annotations (@Entity, @Id, @Column) over Hibernate-specific ones so you can switch providers later.
  • Use @Transactional with Spring only if you are already using Spring; for plain Hibernate, manage transactions explicitly.
  • Keep entity classes small and free of business logic; put queries in a repository or DAO class.
  • Log at DEBUG for org.hibernate.SQL when diagnosing query issues.

Troubleshooting

If you get org.hibernate.MappingException: Unknown entity, the entity is not listed in the configuration or is outside the scanned package. Add the mapping entry or check your package names.

If the connection fails, verify the JDBC URL format, that the database is running, and that the driver class matches the database. A wrong dialect often shows up as SQL syntax errors on startup.

If inserts silently do nothing, confirm you called commit() and that the session was not closed before the transaction completed. If you see LazyInitializationException, you are accessing a lazy association after the session closed; fetch it inside the transaction or use a join fetch.

If the build fails with duplicate classes, run mvn dependency:tree and exclude the conflicting artifact. If schema generation creates unexpected columns, compare your field names and @Column annotations with the table definition.

Frequently Asked Questions

Do I need Spring to use Hibernate?

No. Hibernate works standalone with a SessionFactory and explicit transactions. Spring adds convenience such as declarative transactions and dependency injection but is not required.

What is the difference between save and persist?

persist follows JPA semantics and does not guarantee an immediate identifier assignment; save is Hibernate-specific and returns the generated identifier. For new code, prefer persist.

Can Hibernate create my tables automatically?

Yes, via hbm2ddl.auto, but treat it as a development aid. Use migration tools for production schema changes.

Which Hibernate version should I use?

Use a current stable release compatible with your JDK and JPA version. Check the dependency tree to avoid mixing major versions.

Why is my query returning stale data?

The session cache may hold an older copy. Clear the session with session.clear() or use refresh when you need fresh data from the database.