Databases 8 min read

Understanding Hibernate: Benefits, ORM Basics, Query Types, Session Management, Caching, and Entity Rules

This article explains why Hibernate is used, defines ORM, shows how to view SQL logs, describes HQL/SQL/Criteria queries with code examples, discusses entity class design, caching layers, object states, session handling methods, and the requirement for a no‑argument constructor.

Java Captain
Java Captain
Java Captain
Understanding Hibernate: Benefits, ORM Basics, Query Types, Session Management, Caching, and Entity Rules

Hibernate is a mainstream Java persistence framework built on JDBC that encapsulates database access code, greatly simplifies the DAO layer, uses reflection for transparency, and offers high performance with flexible mapping across many relational databases.

ORM (Object‑Relational Mapping) is middleware that maps in‑memory objects to relational tables, allowing developers to work with objects while the framework handles the conversion to SQL.

To view the SQL statements generated by Hibernate, you can enable logging as described in the referenced blog post.

Hibernate supports three query approaches:

HQL (Hibernate Query Language) – object‑oriented queries, e.g.,

Query query = session.createQuery("from Customer where name = ?"); query.setParameter(0, "Example"); query.list();

Criteria (QBC – Query By Criteria) – programmatic conditional queries, e.g.,

Criteria criteria = session.createCriteria(Customer.class); criteria.add(Restrictions.eq("name", "Example")); List<Customer> list = criteria.list();

Native SQL – direct SQL execution, e.g.,

SQLQuery query = session.createSQLQuery("select * from customer"); List<Object[]> list = query.list();

Entity classes can be declared final, but doing so prevents Hibernate from creating proxy subclasses needed for lazy loading, which may degrade performance; using interfaces can mitigate this limitation.

When mapping identifiers, using Integer allows Hibernate to detect transient objects via null values, whereas int requires setting unsaved-value="0" in the mapping file.

Typical Hibernate workflow:

Load configuration: Configuration config = new Configuration().configure(); Parse mapping resources from hibernate.cfg.xml.

Create SessionFactory: SessionFactory sf = config.buildSessionFactory(); Open a Session: Session session = sf.openSession(); Begin a transaction: Transaction tx = session.beginTransaction(); Perform persistent operations (save, update, delete, query).

Commit the transaction: tx.commit(); Close the session and finally the SessionFactory.

The get() method immediately hits the database and returns a fully initialized object, while load() returns a proxy and only queries the database when a non‑identifier property is accessed.

Hibernate caches data at two levels: first‑level cache (session scoped, always enabled) and optional second‑level cache (session‑factory scoped). Suitable data for second‑level caching includes rarely modified, frequently read, non‑critical, or constant data; distributed caches like Memcached or Redis can be used as alternatives.

Entity objects exist in three states:

Transient – newly instantiated, not associated with a session, no identifier.

Persistent – associated with a session after save() or saveOrUpdate(), has an identifier.

Detached – the session has been closed, the object is no longer managed.

Session acquisition differs: openSession() always creates a new session that must be closed manually, whereas getCurrentSession() returns the current transactional session, creating one if none exists, and is preferred in modern applications.

Hibernate requires entity classes to have a no‑argument constructor because it uses Class.newInstance() to instantiate objects; if you define other constructors, you must explicitly provide the default constructor.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSQLcachingORMSessionHibernate
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.