Hibernate

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

Article Summary

Since ORM architecture isn't obvious, this document will explain some important things you need to know in order to analyze a Hibernate application in a security context. This document assumes some SQL and database knowledge. A note about SQL injection Since it is the hot topic, I will address it now but discuss in detail later. Hibernate does not grant immunity to SQL Injection, one...

Key Takeaways

  • This article explains Overview in simple medical language.
  • This article explains Security Implications in simple medical language.
  • This article explains Defining Transaction Bounds in simple medical language.
  • This article explains Creating, manipulating and executing queries in simple medical language.
Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.

Seek urgent medical care if you notice

These warning signs are general safety guidance. Local emergency numbers and clinical judgment should always come first.

  • Severe symptoms, breathing difficulty, fainting, confusion, or rapidly worsening illness.
  • New weakness, severe pain, high fever, or symptoms after a serious injury.
  • Any symptom that feels urgent, unusual, or unsafe for the patient.
1

Emergency now

Use emergency care for severe, sudden, rapidly worsening, or life-threatening symptoms.

2

See a doctor

Book a professional medical evaluation if symptoms persist, worsen, recur often, affect daily activities, or occur in a high-risk patient.

3

Learn safely

Use this article to understand possible causes, tests, treatment options, prevention, and questions to ask your clinician.

Since ORM architecture isn’t obvious, this document will explain some important things you need to know in order to analyze a Hibernate application in a security context. This document assumes some SQL and database knowledge.

A note about SQL injection

Since it is the hot topic, I will address it now but discuss in detail later.

  • Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.
  • There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.
  • Functions such as createQuery(String query) and createSQLQuery(String query) create a Query object that will be executed when the call to commit() is made. If the query string is tainted you have sql injection. The details of these functions are covered later.

Overview

The problem Hibernate addresses

In object oriented systems, we represent entities as objects, and use a database to persist those objects. Generally these objects are considered non-scalar values (non-primitive types). But many databases can only store and manipulate scalar values organized in tables. The crux of the problem is translating those objects to forms which can be stored in the database, and which can later be retrieved easily, while preserving the properties of the objects and their relationships; these objects are then said to be persistent. Hibernate attempts to address this problem with Object/Relational Mapping (O/R M) by mapping attributes of objects we wish to persist to columns of a database.

See original article.

How it works

  • Usually Hibernate applications use JavaBeans style POJOs to represent objects we want to persist in a database.
  • These objects should have an identifier property (i.e private class variable) used to represent it’s primary key value in the database.
  • This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the <id> element. This file will also map all other object properties we wish to preserve to columns in a database table, along with their data types and other stuff.
  • Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.
  • The Session object has methods to save() objects to a session, load() objects from a database and createQuery()s to be executed against the database.
  • The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.
  • Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.
  • Hibernate’s main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc.

See this configuration example

Jargon

  • Transient – The instance is not associated with a Session, has no persistent representation in the database and no identifier assigned. An object that has just been instantiated with the new operator is said to be transient.
  • Persistent – Is associated with a Session, has a representation in the database and has been assigned an identifier. Hibernate synchronizes changes on a persistent object with its representation in the database when it completes a unit of work.
  • Detatched – was once in a persistent state, but its session has been closed. The reference is still valid and the object may be modified and even reattached to a new session later.

Hitting the database

The Session object represents the main interface or conversation between Java and Hibernate. A Session is used for a single request, or unit of work. To make an object persistent, it must first be associated with a Session. But where does the session come from? Hibernate’s Configuration object instantiates a SessionFactory (Configuration.buildSessionFactory()) which is an expensive, immutable, thread safe object intended to be shared by all application threads. Threads that service client requests must obtain a Session from the factory by calling SessionFactory.getCurrentSession() or SessionFactory.openSession().

Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in this section of the Hibernate Guidelines page. Once an object is associated with a Session we can begin a transaction. All database communication must occur within the scope of a transaction. A transaction starts with a call to Transaction.begin() or Session.beginTransaction() and ends with a call to Transaction.commit().

To actually build queries, store and retrieve data we mostly use methods in the Session class. For example, load() will instantiate a class object, and load the state from the database into the instance. Session.createQuery() will return a Query object which has many methods with which to operate on this query string. Query.setParameter()setFloat(), and others act similar to prepared statements. You can also simply call Query.executeUpdate() to execute the query.

Ok, why don’t we just see what it looks like. Example1

Session sess = factory.openSession();
Transaction tx;
try {
     tx = sess.beginTransaction();
     Query q = sess.createQuery("from DomesticCat cat where cat.name = ?");
     q.setString(0, "Izi");
     tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}

Another simple example using HQL and named parameters…this time we have a helper class to obtain a Session

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction(); //All database communication occurs within the scope of a transaction

Person aPerson = (Person) session
        .createQuery("select p from Person p left join fetch p.events where p.id = :pid")
        .setParameter("pid", personId);

session.getTransaction().commit();

Security Implications

These issues are discussed in context on this page and are also listed in this section of Hibernate Guidelines.

  • No communication with the database should occur outside of a database transaction. Doing so will probably result in synchronization issues. Transactions should also not encompass user think time. Details are of how it’s done is discussed in the Defining Transaction Bounds section of this page.
  • createQuery() can easily be passed a tainted SQL or HQL string, dialect is irrelevant. The proper way to construct a sql string hibernate style is to use Query and SQLQuery’s setParameter()setString()setXXX() methods for named parameter and placeholder binding. Just like prepared statements. Details are discussed in the Creating Queries section of this page.
  • An application should rollback and discard Session instance on error. So if the Session throws an exception, the catch block should have rollback() and finally should call Session.close(). This applies to any SQLException. Pretty cut and dry, see Example1 above.
  • You may not mix and match JDBC-style parameters (“?”) and named parameters (:namedparam) in the same query.
 Person aPerson = (Person) session
            .createQuery("select :somenamedparameter from ? where x = :someothernamedparameter");
  • Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely.
 Session sess = factory.openSession();
 try {
      //set transaction timeout to 3 seconds
      sess.getTransaction().setTimeout(3);
      sess.getTransaction().begin();
      // do some work
     ...

Defining Transaction Bounds

Usually, ending a Session involves four distinct phases:

  • flush the session
  • commit the transaction
  • close the session
  • handle exceptions

Note:

  • If commit() is present, no need to call flush() as it does this already.
  • Most database communication methods only propagate exceptions if they’re outside the scope of the session. (this is an assumption based on the many functions whose source I’ve examined, I won’t be perusing the entire api source to back this assumption)

Consider this example:

// Non-managed environment idiom
Session sess = factory.openSession();
Transaction tx = null;
try {
       tx = sess.beginTransaction();
       // do some work
       ...
       tx.commit();
}
catch (RuntimeException e) {
       if (tx != null) tx.rollback();
       throw e; // or display error message
}
finally {
       sess.close();
}

Most Common Functions:

  • Session.beginTransaction() – begin transaction (doh)
  • Session.getTransaction() – begin transaction
  • Session.flush() – end transaction
  • Session.close() – end session
  • Transaction.begin() – begin transaction
  • Transaction.commit() – end transaction
  • Transaction.rollback() –

Creating, manipulating and executing queries

  • The Session interface defines methods that create Query and SQLQuery objects – these are the methods we care about because they allow the developer to construct query strings (as opposed to letting Hibernate perform the sql operations).
  • The Query/SQLQuery objects are mutable and executable, but are not actually SUNK until Transaction.commit(), or Query.executeUpdate() is called. However, I think it is best that we flag functions that create and construct Query objects as they would be in direct contact with tainted data.
  • Once a Query or SQLQuery object is obtained from the Session, the parameters of its sql string should be set using the setter functions like setParameter(), the setters are listed here. These setters check for type mismatch, or guess the type, then check for positional mismatch and named parameter mismatch so they’re pretty safe me thinks. Concatenating tainted parameters using the ‘+’ operator, on the other hand, would be equivalent to mis-using a prepared-statement.

Consider this example:

 String table = (String) req.getParameter("table");//obviously prone to tainted input
 String parameter1 = request.getParameter("param1");

 Session session = sessionFactory.getCurrentSession();
 try{
      session.beginTransaction();
            SQLQuery query = session.createSQLQuery("SELECT * FROM " + table + "WHERE stuff= ?"); /*Boo*/
            query.setParameter(0, parameter1); /*YAY*/
      session.getTransaction().commit();
 } catch (Exception e) {}
 session.close();//omfg no rollback?

Most Common Functions:

  • Session.createSQLQuery(String queryString) – creates a Query with given SQL string – technically executed on commit() or flush() but this function is more directly related to the taint source.
  • Session.createQuery(String queryString) – creates Query with given HQL string.
  • Session.createFilter(Object collection, String queryString) – creates a Query with filter string.
  • Query.setParameter() – variations on this binds parameters to “?” and “:namedparams”
  • Query.executeUpdate() –
  • Query.getQueryString() –

More Examples

Using queries from other Queries:

 String sql;

 session.beginTransaction();
      Query q1 = session.createQuery(taintSQL); //pretend taintSQL came from unchecked input
      sql = q1.getQueryString(); //get taintSQL
 session.getTransaction.commit();

 session.beginTransaction();
      Query q2 = new QueryImpl(sql, session, parameterMetadata); //reuse taintSQL w/o validation
      session.getTransaction.commit(); //evil prevails
 session.close();

Using executeUpdate()

 public void executeUpdateHQL(Session session, String evil)//a few calls deep from where evil became tainted
{
  Query query = session.createQuery(evil);  /*Boo*/
  query.setString("name","Evil");
  query.setString("newName","EEvil"); //these don't matter if the sql is already evil
  int rowCount = query.executeUpdate();  /*Boo*/
  System.out.println("Rows affected: " + rowCount);

  //See the results of the update and some other random stuff
  query = session.createQuery("from Supplier");
  List results = query.list();

  displaySupplierList(results);
}

named parameter (preferred)

Query q = sess.createQuery("from DomesticCat cat where cat.name = :name");
q.setString("name", "Fritz");
Iterator cats = q.iterate();

positional parameter

Query q = sess.createQuery("from DomesticCat cat where cat.name = ?");
q.setString(0, "Izi");
Iterator cats = q.iterate();

named parameter list

List names = new ArrayList();
names.add("Izi");
names.add("Fritz");
Query q = sess.createQuery("from DomesticCat cat where cat.name in (:namesList)");
q.setParameterList("namesList", names);
List cats = q.list();

Executing a bunch of actions (relevant fns listed in the excel sheet)

private List executions;
    ....
executions = new LinkedList();
    ....
private void executeActions(List list) throws HibernateException {
    for ( Iterator execItr = list.iterator(); execItr.hasNext(); ) {
        execute( (Executable) execItr.next() );
    }
    list.clear();
    session.getBatcher().executeBatch();
}
public void execute(Executable executable) {
    final boolean lockQueryCache = session.getFactory().getSettings().isQueryCacheEnabled();
    if ( executable.hasAfterTransactionCompletion() || lockQueryCache ) {
        executions.add( executable );
    }
    if (lockQueryCache) {
        session.getFactory()
            .getUpdateTimestampsCache()
            .preinvalidate( executable.getPropertySpaces() );
    }
    executable.execute();
}

Persisting tainted data

  • Assume persistent objects have JavaBeans style setter methods as this is most common practice. When these setters are called with tainted parameters consider this object to be tainted.
  • We should flag all functions where tainted objects are made persistent. Although most documents will define Session.save() or Session.persist() as making an object persistent, it is actually PENDING until a call to Transaction.commit() is made. Whether or not we want to flag the saves, or the commits is up to scan dev – keep in mind that if we’re flagging commit() we must first decide that the code between Transaction.begin() or Session.beginTransaction() and Transaction.commit() contains evil.
  • The only associated cwe I can think of right now is stored xss.

Consider this example:

 Session session  = sessionFactory.getCurrentSession();
 String firstname = request.getParameter("firstname");
 String lastname  = request.getParameter("lastname");

 try{
      Transaction tx = session.beginTransaction();

      Person thePerson = session.load(Person.class, new Long(69));//loading an already persistent object
      thePerson.setFirstname(firstname);// then adding tainted data to it
      thePerson.setLastname(lastname);
      session.save(thePerson);  //persisting our changes

      session.getTransaction().commit();
 } catch (Exception e) {
      if (tx!=null) tx.rollback();
      throw e;
 }
     session.close();

Most Common Functions:

  • Session.save(Object object) – save object to the session, object should not contain tainted data.
  • Session.persist(Object object) –
  • Session.void replicate(Object object, ReplicationMode?? replicationMode) –
  • Session.void saveOrUpdate(Object object) –
  • Session.update(Object object) –
  • Session.evict(Object object) – remove instance from session cache
  • Session.clear() – evict all loaded instances
  • Session.load(Class theClass, Serializable id) – gets an object from the db for you to manipulate
Patient safety assistant

Check your symptom safely

Hi, I am RX Symptom Navigator. I can help you understand what to read next and what warning signs need care.
Warning: Do not use this in emergencies, pregnancy, severe illness, or as a substitute for a doctor. For children or teens, use with a parent/guardian and clinician.
A rural-friendly guide: warning signs, when to see a doctor, related articles, tests to discuss, and OTC safety education.
1 Symptom 2 Severity 3 Safe guidance
First safety question

Is there chest pain, breathing trouble, fainting, confusion, severe bleeding, stroke-like weakness, severe injury, or pregnancy danger sign?

Choose quickly

Browse by body area
Start here: Write or select a symptom. The guide will show warning signs, doctor guidance, diagnostic tests to discuss, OTC safety education, and related RX articles.

Important: This tool is educational only. It cannot diagnose, treat, or replace a doctor. OTC information is not a prescription. In an emergency, contact local emergency services or go to the nearest hospital.

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Avoid heavy lifting, sudden bending, and prolonged bed rest.
  • Use comfortable posture and gentle movement as tolerated.
  • Discuss physiotherapy, X-ray, or MRI only when clinically needed.

OTC medicine safety

  • For mild back pain, pain-relief medicine may be discussed with a doctor or pharmacist.
  • Avoid repeated painkiller use if you have kidney disease, stomach ulcer, uncontrolled blood pressure, or are taking blood thinners.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Back pain with leg weakness, numbness around private area, loss of urine/stool control, fever, cancer history, or major injury needs urgent care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Back pain care roadmap

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • New leg weakness, numbness around private area, or loss of bladder/bowel control
  • Back pain after major injury, fever, unexplained weight loss, cancer history, or severe night pain
Doctor / service to discuss: Orthopedic/spine specialist, physical medicine doctor, physiotherapist under guidance, or qualified clinician.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Discuss neurological examination first. X-ray or MRI may be needed only when red flags, injury, nerve weakness, or persistent severe symptoms are present.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.
  • Avoid forceful massage or bone-setting when there is weakness, injury, fever, or nerve symptoms.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

RX Patient Help

Ask a health question safely

Write your symptom story. A health professional or site editor can review it before any answer is prepared. This box is not for emergency care.

Emergency first: Severe chest pain, breathing trouble, unconsciousness, stroke signs, severe injury, heavy bleeding, or rapidly worsening symptoms need urgent local medical care now.

Frequently Asked Questions

Is this article a replacement for a doctor?

No. It is educational content only. Patients should consult a qualified clinician for diagnosis and treatment.

When should I seek urgent care?

Seek urgent care for severe symptoms, rapidly worsening condition, breathing difficulty, severe pain, neurological changes, or any emergency warning sign.

References

Add references, clinical guidelines, textbooks, journal articles, or trusted medical sources here. You can edit this area from the RX Article Professional Blocks panel.