<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Tehmina</id>
		<title>OWASP - User contributions [en]</title>
		<link rel="self" type="application/atom+xml" href="https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Tehmina"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Tehmina"/>
		<updated>2026-05-06T10:10:11Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30522</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30522"/>
				<updated>2008-06-05T18:41:18Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. &lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  &lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;br /&gt;
[[Category:OWASP Java Project]]&lt;br /&gt;
[[Category:Java]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30519</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30519"/>
				<updated>2008-06-05T18:37:43Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;br /&gt;
[[Category:OWASP Java Project]]&lt;br /&gt;
[[Category:Java]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30518</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30518"/>
				<updated>2008-06-05T18:37:28Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Persisting tainted data */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
Usually, ending a Session involves four distinct phases:&lt;br /&gt;
&lt;br /&gt;
* flush the session&lt;br /&gt;
* commit the transaction&lt;br /&gt;
* close the session&lt;br /&gt;
* handle exceptions &lt;br /&gt;
&lt;br /&gt;
Note:&lt;br /&gt;
* If commit() is present, no need to call flush() as it does this already.&lt;br /&gt;
* 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) &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
       // Non-managed environment idiom&lt;br /&gt;
       Session sess = factory.openSession();&lt;br /&gt;
       Transaction tx = null;&lt;br /&gt;
       try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              // do some work&lt;br /&gt;
              ...&lt;br /&gt;
              tx.commit();&lt;br /&gt;
       }&lt;br /&gt;
       catch (RuntimeException e) {&lt;br /&gt;
              if (tx != null) tx.rollback();&lt;br /&gt;
              throw e; // or display error message&lt;br /&gt;
       }&lt;br /&gt;
       finally {&lt;br /&gt;
              sess.close();&lt;br /&gt;
       }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.beginTransaction() - begin transaction (doh)&lt;br /&gt;
* Session.getTransaction() - begin transaction&lt;br /&gt;
* Session.flush() - end transaction&lt;br /&gt;
* Session.close() - end session&lt;br /&gt;
* Transaction.begin() - begin transaction&lt;br /&gt;
* Transaction.commit() - end transaction&lt;br /&gt;
* Transaction.rollback() -&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
* 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).&lt;br /&gt;
* 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. &lt;br /&gt;
* Once a Query or SQLQuery object is obtained from the Session, the parameters of it's 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. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String table = (String) req.getParameter(&amp;quot;table&amp;quot;);//obviously retarded&lt;br /&gt;
     String parameter1 = request.getParameter(&amp;quot;param1&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     try{&lt;br /&gt;
          session.beginTransaction();&lt;br /&gt;
                SQLQuery query = session.createSQLQuery(&amp;quot;SELECT * FROM &amp;quot; + table + &amp;quot;WHERE stuff= ?&amp;quot;); /*B00*/&lt;br /&gt;
                query.setParameter(0, parameter1); /*YAY*/&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {} &lt;br /&gt;
     session.close();//omfg no rollback?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* Session.createQuery(String queryString) - creates Query with given HQL string.&lt;br /&gt;
* Session.createFilter(Object collection, String queryString) - creates a Query with filter string.&lt;br /&gt;
* Query.setParameter() - variations on this binds parameters to &amp;quot;?&amp;quot; and &amp;quot;:namedparams&amp;quot;&lt;br /&gt;
* Query.executeUpdate() -&lt;br /&gt;
* Query.getQueryString() -&lt;br /&gt;
&lt;br /&gt;
==== More Examples ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using queries from other Query's:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String sql;&lt;br /&gt;
&lt;br /&gt;
     session.beginTransaction();&lt;br /&gt;
          Query q1 = session.createQuery(taintSQL); //pretend taintSQL came from unchecked input&lt;br /&gt;
          sql = q1.getQueryString(); //get taintSQL&lt;br /&gt;
     session.getTransaction.commit();&lt;br /&gt;
     &lt;br /&gt;
     session.beginTransaction();&lt;br /&gt;
          Query q2 = new QueryImpl(sql, session, parameterMetadata); //reuse taintSQL w/o validation&lt;br /&gt;
          session.getTransaction.commit(); //evil prevails&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Using executeUpdate()&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     public void executeUpdateHQL(Session session, String evil)//a few calls deep from where evil became tainted&lt;br /&gt;
        {&lt;br /&gt;
          Query query = session.createQuery(evil);  /*B00*/&lt;br /&gt;
          query.setString(&amp;quot;name&amp;quot;,&amp;quot;Evil&amp;quot;);&lt;br /&gt;
          query.setString(&amp;quot;newName&amp;quot;,&amp;quot;EEvil&amp;quot;); //these don't matter if the sql is already evil&lt;br /&gt;
          int rowCount = query.executeUpdate();  /*B00*/&lt;br /&gt;
          System.out.println(&amp;quot;Rows affected: &amp;quot; + rowCount);&lt;br /&gt;
&lt;br /&gt;
          //See the results of the update and some other random stuff&lt;br /&gt;
          query = session.createQuery(&amp;quot;from Supplier&amp;quot;);&lt;br /&gt;
          List results = query.list();            &lt;br /&gt;
&lt;br /&gt;
          displaySupplierList(results);            &lt;br /&gt;
        }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
named parameter (preferred)&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = :name&amp;quot;);&lt;br /&gt;
q.setString(&amp;quot;name&amp;quot;, &amp;quot;Fritz&amp;quot;);&lt;br /&gt;
Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
positional parameter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
named parameter list&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
List names = new ArrayList();&lt;br /&gt;
names.add(&amp;quot;Izi&amp;quot;);&lt;br /&gt;
names.add(&amp;quot;Fritz&amp;quot;);&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name in (:namesList)&amp;quot;);&lt;br /&gt;
q.setParameterList(&amp;quot;namesList&amp;quot;, names);&lt;br /&gt;
List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Executing a bunch of actions (relevant fns listed in the excel sheet)&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	private List executions;&lt;br /&gt;
		....&lt;br /&gt;
	executions = new LinkedList();&lt;br /&gt;
		....&lt;br /&gt;
	private void executeActions(List list) throws HibernateException {&lt;br /&gt;
		for ( Iterator execItr = list.iterator(); execItr.hasNext(); ) {&lt;br /&gt;
			execute( (Executable) execItr.next() );&lt;br /&gt;
		}&lt;br /&gt;
		list.clear();&lt;br /&gt;
		session.getBatcher().executeBatch();&lt;br /&gt;
	}&lt;br /&gt;
	public void execute(Executable executable) {&lt;br /&gt;
		final boolean lockQueryCache = session.getFactory().getSettings().isQueryCacheEnabled();&lt;br /&gt;
		if ( executable.hasAfterTransactionCompletion() || lockQueryCache ) {&lt;br /&gt;
			executions.add( executable );&lt;br /&gt;
		}&lt;br /&gt;
		if (lockQueryCache) {&lt;br /&gt;
			session.getFactory()&lt;br /&gt;
				.getUpdateTimestampsCache()&lt;br /&gt;
				.preinvalidate( executable.getPropertySpaces() );&lt;br /&gt;
		}&lt;br /&gt;
		executable.execute();&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* 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 eevil.&lt;br /&gt;
* The only associated cwe I can think of right now is stored xss. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     String firstname = req.getParameter(&amp;quot;firstname&amp;quot;);&lt;br /&gt;
     String lastname = request.getParameter(&amp;quot;lastname&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     try{&lt;br /&gt;
          Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
          Person thePerson = session.load(Person.class, new Long(69));//loading an already persistent object&lt;br /&gt;
          thePerson.setFirstname(firstname);// then adding tainted data to it&lt;br /&gt;
          thePerson.setLastname(lastname);&lt;br /&gt;
          session.save(thePerson);  //persisting our changes&lt;br /&gt;
&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {&lt;br /&gt;
          if (tx!=null) tx.rollback();&lt;br /&gt;
          throw e;&lt;br /&gt;
     } &lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.save(Object object) - save object to the session, object should not contain tainted data.&lt;br /&gt;
* Session.persist(Object object) -&lt;br /&gt;
* Session.void replicate(Object object, ReplicationMode?? replicationMode) -&lt;br /&gt;
* Session.void saveOrUpdate(Object object) -&lt;br /&gt;
* Session.update(Object object)() -&lt;br /&gt;
* Session.evict(Object object)() - remove instance from session cache&lt;br /&gt;
* Session.clear() - evict all loaded instances&lt;br /&gt;
* Session.load(Class theClass, Serializable id) - gets an object from the db for you to manipulate. &lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;br /&gt;
[[Category:OWASP Java Project]]&lt;br /&gt;
[[Category:Java]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30516</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30516"/>
				<updated>2008-06-05T18:35:16Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
Usually, ending a Session involves four distinct phases:&lt;br /&gt;
&lt;br /&gt;
* flush the session&lt;br /&gt;
* commit the transaction&lt;br /&gt;
* close the session&lt;br /&gt;
* handle exceptions &lt;br /&gt;
&lt;br /&gt;
Note:&lt;br /&gt;
* If commit() is present, no need to call flush() as it does this already.&lt;br /&gt;
* 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) &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
       // Non-managed environment idiom&lt;br /&gt;
       Session sess = factory.openSession();&lt;br /&gt;
       Transaction tx = null;&lt;br /&gt;
       try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              // do some work&lt;br /&gt;
              ...&lt;br /&gt;
              tx.commit();&lt;br /&gt;
       }&lt;br /&gt;
       catch (RuntimeException e) {&lt;br /&gt;
              if (tx != null) tx.rollback();&lt;br /&gt;
              throw e; // or display error message&lt;br /&gt;
       }&lt;br /&gt;
       finally {&lt;br /&gt;
              sess.close();&lt;br /&gt;
       }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.beginTransaction() - begin transaction (doh)&lt;br /&gt;
* Session.getTransaction() - begin transaction&lt;br /&gt;
* Session.flush() - end transaction&lt;br /&gt;
* Session.close() - end session&lt;br /&gt;
* Transaction.begin() - begin transaction&lt;br /&gt;
* Transaction.commit() - end transaction&lt;br /&gt;
* Transaction.rollback() -&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
* 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).&lt;br /&gt;
* 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. &lt;br /&gt;
* Once a Query or SQLQuery object is obtained from the Session, the parameters of it's 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. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String table = (String) req.getParameter(&amp;quot;table&amp;quot;);//obviously retarded&lt;br /&gt;
     String parameter1 = request.getParameter(&amp;quot;param1&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     try{&lt;br /&gt;
          session.beginTransaction();&lt;br /&gt;
                SQLQuery query = session.createSQLQuery(&amp;quot;SELECT * FROM &amp;quot; + table + &amp;quot;WHERE stuff= ?&amp;quot;); /*B00*/&lt;br /&gt;
                query.setParameter(0, parameter1); /*YAY*/&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {} &lt;br /&gt;
     session.close();//omfg no rollback?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* Session.createQuery(String queryString) - creates Query with given HQL string.&lt;br /&gt;
* Session.createFilter(Object collection, String queryString) - creates a Query with filter string.&lt;br /&gt;
* Query.setParameter() - variations on this binds parameters to &amp;quot;?&amp;quot; and &amp;quot;:namedparams&amp;quot;&lt;br /&gt;
* Query.executeUpdate() -&lt;br /&gt;
* Query.getQueryString() -&lt;br /&gt;
&lt;br /&gt;
==== More Examples ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using queries from other Query's:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String sql;&lt;br /&gt;
&lt;br /&gt;
     session.beginTransaction();&lt;br /&gt;
          Query q1 = session.createQuery(taintSQL); //pretend taintSQL came from unchecked input&lt;br /&gt;
          sql = q1.getQueryString(); //get taintSQL&lt;br /&gt;
     session.getTransaction.commit();&lt;br /&gt;
     &lt;br /&gt;
     session.beginTransaction();&lt;br /&gt;
          Query q2 = new QueryImpl(sql, session, parameterMetadata); //reuse taintSQL w/o validation&lt;br /&gt;
          session.getTransaction.commit(); //evil prevails&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Using executeUpdate()&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     public void executeUpdateHQL(Session session, String evil)//a few calls deep from where evil became tainted&lt;br /&gt;
        {&lt;br /&gt;
          Query query = session.createQuery(evil);  /*B00*/&lt;br /&gt;
          query.setString(&amp;quot;name&amp;quot;,&amp;quot;Evil&amp;quot;);&lt;br /&gt;
          query.setString(&amp;quot;newName&amp;quot;,&amp;quot;EEvil&amp;quot;); //these don't matter if the sql is already evil&lt;br /&gt;
          int rowCount = query.executeUpdate();  /*B00*/&lt;br /&gt;
          System.out.println(&amp;quot;Rows affected: &amp;quot; + rowCount);&lt;br /&gt;
&lt;br /&gt;
          //See the results of the update and some other random stuff&lt;br /&gt;
          query = session.createQuery(&amp;quot;from Supplier&amp;quot;);&lt;br /&gt;
          List results = query.list();            &lt;br /&gt;
&lt;br /&gt;
          displaySupplierList(results);            &lt;br /&gt;
        }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
named parameter (preferred)&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = :name&amp;quot;);&lt;br /&gt;
q.setString(&amp;quot;name&amp;quot;, &amp;quot;Fritz&amp;quot;);&lt;br /&gt;
Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
positional parameter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
named parameter list&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
List names = new ArrayList();&lt;br /&gt;
names.add(&amp;quot;Izi&amp;quot;);&lt;br /&gt;
names.add(&amp;quot;Fritz&amp;quot;);&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name in (:namesList)&amp;quot;);&lt;br /&gt;
q.setParameterList(&amp;quot;namesList&amp;quot;, names);&lt;br /&gt;
List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Executing a bunch of actions (relevant fns listed in the excel sheet)&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	private List executions;&lt;br /&gt;
		....&lt;br /&gt;
	executions = new LinkedList();&lt;br /&gt;
		....&lt;br /&gt;
	private void executeActions(List list) throws HibernateException {&lt;br /&gt;
		for ( Iterator execItr = list.iterator(); execItr.hasNext(); ) {&lt;br /&gt;
			execute( (Executable) execItr.next() );&lt;br /&gt;
		}&lt;br /&gt;
		list.clear();&lt;br /&gt;
		session.getBatcher().executeBatch();&lt;br /&gt;
	}&lt;br /&gt;
	public void execute(Executable executable) {&lt;br /&gt;
		final boolean lockQueryCache = session.getFactory().getSettings().isQueryCacheEnabled();&lt;br /&gt;
		if ( executable.hasAfterTransactionCompletion() || lockQueryCache ) {&lt;br /&gt;
			executions.add( executable );&lt;br /&gt;
		}&lt;br /&gt;
		if (lockQueryCache) {&lt;br /&gt;
			session.getFactory()&lt;br /&gt;
				.getUpdateTimestampsCache()&lt;br /&gt;
				.preinvalidate( executable.getPropertySpaces() );&lt;br /&gt;
		}&lt;br /&gt;
		executable.execute();&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* 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 eevil.&lt;br /&gt;
* The only associated cwe I can think of right now is stored xss. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     String firstname = req.getParameter(&amp;quot;firstname&amp;quot;);&lt;br /&gt;
     String lastname = request.getParameter(&amp;quot;lastname&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     try{&lt;br /&gt;
          Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
          Person thePerson = session.load(Person.class, new Long(69));//loading an already persistent object&lt;br /&gt;
          thePerson.setFirstname(firstname);// then adding tainted data to it&lt;br /&gt;
          thePerson.setLastname(lastname);&lt;br /&gt;
          session.save(thePerson);  //persisting our changes&lt;br /&gt;
&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {&lt;br /&gt;
          if (tx!=null) tx.rollback();&lt;br /&gt;
          throw e;&lt;br /&gt;
     } &lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.save(Object object) - save object to the session, object should not contain tainted data.&lt;br /&gt;
* Session.persist(Object object) -&lt;br /&gt;
* Session.void replicate(Object object, ReplicationMode?? replicationMode) -&lt;br /&gt;
* Session.void saveOrUpdate(Object object) -&lt;br /&gt;
* Session.update(Object object)() -&lt;br /&gt;
* Session.evict(Object object)() - remove instance from session cache&lt;br /&gt;
* Session.clear() - evict all loaded instances&lt;br /&gt;
* Session.load(Class theClass, Serializable id) - gets an object from the db for you to manipulate. &lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30501</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30501"/>
				<updated>2008-06-05T17:31:00Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Creating, manipulating and executing queries */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
Usually, ending a Session involves four distinct phases:&lt;br /&gt;
&lt;br /&gt;
* flush the session&lt;br /&gt;
* commit the transaction&lt;br /&gt;
* close the session&lt;br /&gt;
* handle exceptions &lt;br /&gt;
&lt;br /&gt;
Note:&lt;br /&gt;
* If commit() is present, no need to call flush() as it does this already.&lt;br /&gt;
* 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) &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
       // Non-managed environment idiom&lt;br /&gt;
       Session sess = factory.openSession();&lt;br /&gt;
       Transaction tx = null;&lt;br /&gt;
       try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              // do some work&lt;br /&gt;
              ...&lt;br /&gt;
              tx.commit();&lt;br /&gt;
       }&lt;br /&gt;
       catch (RuntimeException e) {&lt;br /&gt;
              if (tx != null) tx.rollback();&lt;br /&gt;
              throw e; // or display error message&lt;br /&gt;
       }&lt;br /&gt;
       finally {&lt;br /&gt;
              sess.close();&lt;br /&gt;
       }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.beginTransaction() - begin transaction (doh)&lt;br /&gt;
* Session.getTransaction() - begin transaction&lt;br /&gt;
* Session.flush() - end transaction&lt;br /&gt;
* Session.close() - end session&lt;br /&gt;
* Transaction.begin() - begin transaction&lt;br /&gt;
* Transaction.commit() - end transaction&lt;br /&gt;
* Transaction.rollback() -&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
* 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).&lt;br /&gt;
* 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. &lt;br /&gt;
* Once a Query or SQLQuery object is obtained from the Session, the parameters of it's 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. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String table = (String) req.getParameter(&amp;quot;table&amp;quot;);//obviously retarded&lt;br /&gt;
     String parameter1 = request.getParameter(&amp;quot;param1&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     try{&lt;br /&gt;
          session.beginTransaction();&lt;br /&gt;
                SQLQuery query = session.createSQLQuery(&amp;quot;SELECT * FROM &amp;quot; + table + &amp;quot;WHERE stuff= ?&amp;quot;); /*B00*/&lt;br /&gt;
                query.setParameter(0, parameter1); /*YAY*/&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {} &lt;br /&gt;
     session.close();//omfg no rollback?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* Session.createQuery(String queryString) - creates Query with given HQL string.&lt;br /&gt;
* Session.createFilter(Object collection, String queryString) - creates a Query with filter string.&lt;br /&gt;
* Query.setParameter() - variations on this binds parameters to &amp;quot;?&amp;quot; and &amp;quot;:namedparams&amp;quot;&lt;br /&gt;
* Query.executeUpdate() -&lt;br /&gt;
* Query.getQueryString() -&lt;br /&gt;
&lt;br /&gt;
==== More Examples ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Using queries from other Query's:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String sql;&lt;br /&gt;
&lt;br /&gt;
     session.beginTransaction();&lt;br /&gt;
          Query q1 = session.createQuery(taintSQL); //pretend taintSQL came from unchecked input&lt;br /&gt;
          sql = q1.getQueryString(); //get taintSQL&lt;br /&gt;
     session.getTransaction.commit();&lt;br /&gt;
     &lt;br /&gt;
     session.beginTransaction();&lt;br /&gt;
          Query q2 = new QueryImpl(sql, session, parameterMetadata); //reuse taintSQL w/o validation&lt;br /&gt;
          session.getTransaction.commit(); //evil prevails&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Using executeUpdate()&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     public void executeUpdateHQL(Session session, String evil)//a few calls deep from where evil became tainted&lt;br /&gt;
        {&lt;br /&gt;
          Query query = session.createQuery(evil);  /*B00*/&lt;br /&gt;
          query.setString(&amp;quot;name&amp;quot;,&amp;quot;Evil&amp;quot;);&lt;br /&gt;
          query.setString(&amp;quot;newName&amp;quot;,&amp;quot;EEvil&amp;quot;); //these don't matter if the sql is already evil&lt;br /&gt;
          int rowCount = query.executeUpdate();  /*B00*/&lt;br /&gt;
          System.out.println(&amp;quot;Rows affected: &amp;quot; + rowCount);&lt;br /&gt;
&lt;br /&gt;
          //See the results of the update and some other random stuff&lt;br /&gt;
          query = session.createQuery(&amp;quot;from Supplier&amp;quot;);&lt;br /&gt;
          List results = query.list();            &lt;br /&gt;
&lt;br /&gt;
          displaySupplierList(results);            &lt;br /&gt;
        }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
named parameter (preferred)&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = :name&amp;quot;);&lt;br /&gt;
q.setString(&amp;quot;name&amp;quot;, &amp;quot;Fritz&amp;quot;);&lt;br /&gt;
Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
positional parameter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
named parameter list&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
List names = new ArrayList();&lt;br /&gt;
names.add(&amp;quot;Izi&amp;quot;);&lt;br /&gt;
names.add(&amp;quot;Fritz&amp;quot;);&lt;br /&gt;
Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name in (:namesList)&amp;quot;);&lt;br /&gt;
q.setParameterList(&amp;quot;namesList&amp;quot;, names);&lt;br /&gt;
List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Executing a bunch of actions (relevant fns listed in the excel sheet)&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	private List executions;&lt;br /&gt;
		....&lt;br /&gt;
	executions = new LinkedList();&lt;br /&gt;
		....&lt;br /&gt;
	private void executeActions(List list) throws HibernateException {&lt;br /&gt;
		for ( Iterator execItr = list.iterator(); execItr.hasNext(); ) {&lt;br /&gt;
			execute( (Executable) execItr.next() );&lt;br /&gt;
		}&lt;br /&gt;
		list.clear();&lt;br /&gt;
		session.getBatcher().executeBatch();&lt;br /&gt;
	}&lt;br /&gt;
	public void execute(Executable executable) {&lt;br /&gt;
		final boolean lockQueryCache = session.getFactory().getSettings().isQueryCacheEnabled();&lt;br /&gt;
		if ( executable.hasAfterTransactionCompletion() || lockQueryCache ) {&lt;br /&gt;
			executions.add( executable );&lt;br /&gt;
		}&lt;br /&gt;
		if (lockQueryCache) {&lt;br /&gt;
			session.getFactory()&lt;br /&gt;
				.getUpdateTimestampsCache()&lt;br /&gt;
				.preinvalidate( executable.getPropertySpaces() );&lt;br /&gt;
		}&lt;br /&gt;
		executable.execute();&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* 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 eevil.&lt;br /&gt;
* The only associated cwe I can think of right now is stored xss. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     String firstname = req.getParameter(&amp;quot;firstname&amp;quot;);&lt;br /&gt;
     String lastname = request.getParameter(&amp;quot;lastname&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     try{&lt;br /&gt;
          Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
          Person thePerson = session.load(Person.class, new Long(69));//loading an already persistent object&lt;br /&gt;
          thePerson.setFirstname(firstname);// then adding tainted data to it&lt;br /&gt;
          thePerson.setLastname(lastname);&lt;br /&gt;
          session.save(thePerson);  //persisting our changes&lt;br /&gt;
&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {&lt;br /&gt;
          if (tx!=null) tx.rollback();&lt;br /&gt;
          throw e;&lt;br /&gt;
     } &lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.save(Object object) - save object to the session, object should not contain tainted data.&lt;br /&gt;
* Session.persist(Object object) -&lt;br /&gt;
* Session.void replicate(Object object, ReplicationMode?? replicationMode) -&lt;br /&gt;
* Session.void saveOrUpdate(Object object) -&lt;br /&gt;
* Session.update(Object object)() -&lt;br /&gt;
* Session.evict(Object object)() - remove instance from session cache&lt;br /&gt;
* Session.clear() - evict all loaded instances&lt;br /&gt;
* Session.load(Class theClass, Serializable id) - gets an object from the db for you to manipulate. &lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30500</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30500"/>
				<updated>2008-06-05T17:28:37Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Persisting tainted data */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
Usually, ending a Session involves four distinct phases:&lt;br /&gt;
&lt;br /&gt;
* flush the session&lt;br /&gt;
* commit the transaction&lt;br /&gt;
* close the session&lt;br /&gt;
* handle exceptions &lt;br /&gt;
&lt;br /&gt;
Note:&lt;br /&gt;
* If commit() is present, no need to call flush() as it does this already.&lt;br /&gt;
* 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) &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
       // Non-managed environment idiom&lt;br /&gt;
       Session sess = factory.openSession();&lt;br /&gt;
       Transaction tx = null;&lt;br /&gt;
       try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              // do some work&lt;br /&gt;
              ...&lt;br /&gt;
              tx.commit();&lt;br /&gt;
       }&lt;br /&gt;
       catch (RuntimeException e) {&lt;br /&gt;
              if (tx != null) tx.rollback();&lt;br /&gt;
              throw e; // or display error message&lt;br /&gt;
       }&lt;br /&gt;
       finally {&lt;br /&gt;
              sess.close();&lt;br /&gt;
       }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.beginTransaction() - begin transaction (doh)&lt;br /&gt;
* Session.getTransaction() - begin transaction&lt;br /&gt;
* Session.flush() - end transaction&lt;br /&gt;
* Session.close() - end session&lt;br /&gt;
* Transaction.begin() - begin transaction&lt;br /&gt;
* Transaction.commit() - end transaction&lt;br /&gt;
* Transaction.rollback() -&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
* 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).&lt;br /&gt;
* 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. &lt;br /&gt;
* Once a Query or SQLQuery object is obtained from the Session, the parameters of it's 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. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String table = (String) req.getParameter(&amp;quot;table&amp;quot;);//obviously retarded&lt;br /&gt;
     String parameter1 = request.getParameter(&amp;quot;param1&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     try{&lt;br /&gt;
          session.beginTransaction();&lt;br /&gt;
                SQLQuery query = session.createSQLQuery(&amp;quot;SELECT * FROM &amp;quot; + table + &amp;quot;WHERE stuff= ?&amp;quot;); /*B00*/&lt;br /&gt;
                query.setParameter(0, parameter1); /*YAY*/&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {} &lt;br /&gt;
     session.close();//omfg no rollback?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* Session.createQuery(String queryString) - creates Query with given HQL string.&lt;br /&gt;
* Session.createFilter(Object collection, String queryString) - creates a Query with filter string.&lt;br /&gt;
* Query.setParameter() - variations on this binds parameters to &amp;quot;?&amp;quot; and &amp;quot;:namedparams&amp;quot;&lt;br /&gt;
* Query.executeUpdate() -&lt;br /&gt;
* Query.getQueryString() -&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* 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 eevil.&lt;br /&gt;
* The only associated cwe I can think of right now is stored xss. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     String firstname = req.getParameter(&amp;quot;firstname&amp;quot;);&lt;br /&gt;
     String lastname = request.getParameter(&amp;quot;lastname&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     try{&lt;br /&gt;
          Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
          Person thePerson = session.load(Person.class, new Long(69));//loading an already persistent object&lt;br /&gt;
          thePerson.setFirstname(firstname);// then adding tainted data to it&lt;br /&gt;
          thePerson.setLastname(lastname);&lt;br /&gt;
          session.save(thePerson);  //persisting our changes&lt;br /&gt;
&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {&lt;br /&gt;
          if (tx!=null) tx.rollback();&lt;br /&gt;
          throw e;&lt;br /&gt;
     } &lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.save(Object object) - save object to the session, object should not contain tainted data.&lt;br /&gt;
* Session.persist(Object object) -&lt;br /&gt;
* Session.void replicate(Object object, ReplicationMode?? replicationMode) -&lt;br /&gt;
* Session.void saveOrUpdate(Object object) -&lt;br /&gt;
* Session.update(Object object)() -&lt;br /&gt;
* Session.evict(Object object)() - remove instance from session cache&lt;br /&gt;
* Session.clear() - evict all loaded instances&lt;br /&gt;
* Session.load(Class theClass, Serializable id) - gets an object from the db for you to manipulate. &lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30499</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30499"/>
				<updated>2008-06-05T17:27:20Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Creating, manipulating and executing queries */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
Usually, ending a Session involves four distinct phases:&lt;br /&gt;
&lt;br /&gt;
* flush the session&lt;br /&gt;
* commit the transaction&lt;br /&gt;
* close the session&lt;br /&gt;
* handle exceptions &lt;br /&gt;
&lt;br /&gt;
Note:&lt;br /&gt;
* If commit() is present, no need to call flush() as it does this already.&lt;br /&gt;
* 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) &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
       // Non-managed environment idiom&lt;br /&gt;
       Session sess = factory.openSession();&lt;br /&gt;
       Transaction tx = null;&lt;br /&gt;
       try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              // do some work&lt;br /&gt;
              ...&lt;br /&gt;
              tx.commit();&lt;br /&gt;
       }&lt;br /&gt;
       catch (RuntimeException e) {&lt;br /&gt;
              if (tx != null) tx.rollback();&lt;br /&gt;
              throw e; // or display error message&lt;br /&gt;
       }&lt;br /&gt;
       finally {&lt;br /&gt;
              sess.close();&lt;br /&gt;
       }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.beginTransaction() - begin transaction (doh)&lt;br /&gt;
* Session.getTransaction() - begin transaction&lt;br /&gt;
* Session.flush() - end transaction&lt;br /&gt;
* Session.close() - end session&lt;br /&gt;
* Transaction.begin() - begin transaction&lt;br /&gt;
* Transaction.commit() - end transaction&lt;br /&gt;
* Transaction.rollback() -&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
* 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).&lt;br /&gt;
* 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. &lt;br /&gt;
* Once a Query or SQLQuery object is obtained from the Session, the parameters of it's 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. &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     String table = (String) req.getParameter(&amp;quot;table&amp;quot;);//obviously retarded&lt;br /&gt;
     String parameter1 = request.getParameter(&amp;quot;param1&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
     Session session = sessionFactory.getCurrentSession();&lt;br /&gt;
     try{&lt;br /&gt;
          session.beginTransaction();&lt;br /&gt;
                SQLQuery query = session.createSQLQuery(&amp;quot;SELECT * FROM &amp;quot; + table + &amp;quot;WHERE stuff= ?&amp;quot;); /*B00*/&lt;br /&gt;
                query.setParameter(0, parameter1); /*YAY*/&lt;br /&gt;
          session.getTransaction().commit();&lt;br /&gt;
     } catch (Exception e) {} &lt;br /&gt;
     session.close();//omfg no rollback?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
* Session.createQuery(String queryString) - creates Query with given HQL string.&lt;br /&gt;
* Session.createFilter(Object collection, String queryString) - creates a Query with filter string.&lt;br /&gt;
* Query.setParameter() - variations on this binds parameters to &amp;quot;?&amp;quot; and &amp;quot;:namedparams&amp;quot;&lt;br /&gt;
* Query.executeUpdate() -&lt;br /&gt;
* Query.getQueryString() -&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30498</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30498"/>
				<updated>2008-06-05T17:26:12Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Defining Transaction Bounds */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
Usually, ending a Session involves four distinct phases:&lt;br /&gt;
&lt;br /&gt;
* flush the session&lt;br /&gt;
* commit the transaction&lt;br /&gt;
* close the session&lt;br /&gt;
* handle exceptions &lt;br /&gt;
&lt;br /&gt;
Note:&lt;br /&gt;
* If commit() is present, no need to call flush() as it does this already.&lt;br /&gt;
* 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) &lt;br /&gt;
&lt;br /&gt;
Consider this example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
       // Non-managed environment idiom&lt;br /&gt;
       Session sess = factory.openSession();&lt;br /&gt;
       Transaction tx = null;&lt;br /&gt;
       try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              // do some work&lt;br /&gt;
              ...&lt;br /&gt;
              tx.commit();&lt;br /&gt;
       }&lt;br /&gt;
       catch (RuntimeException e) {&lt;br /&gt;
              if (tx != null) tx.rollback();&lt;br /&gt;
              throw e; // or display error message&lt;br /&gt;
       }&lt;br /&gt;
       finally {&lt;br /&gt;
              sess.close();&lt;br /&gt;
       }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Most Common Functions:&lt;br /&gt;
&lt;br /&gt;
* Session.beginTransaction() - begin transaction (doh)&lt;br /&gt;
* Session.getTransaction() - begin transaction&lt;br /&gt;
* Session.flush() - end transaction&lt;br /&gt;
* Session.close() - end session&lt;br /&gt;
* Transaction.begin() - begin transaction&lt;br /&gt;
* Transaction.commit() - end transaction&lt;br /&gt;
* Transaction.rollback() -&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30497</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30497"/>
				<updated>2008-06-05T17:23:09Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Security Implications */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Defining_Transaction_Bounds Defining Transaction Bounds section] of this page.  &lt;br /&gt;
&lt;br /&gt;
* 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 [http://www.owasp.org/index.php/Hibernate#Creating_Queries Creating Queries section] of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the [http://www.owasp.org/index.php/Hibernate#Persisting_Tainted_Data Persisting Tainted Data section] of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30496</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30496"/>
				<updated>2008-06-05T17:20:04Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Security Implications */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* 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.  &lt;br /&gt;
&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects is stored xss. Since stored XSS is generally hard to find with static tools, it is best to sanitize all data going in rather than waiting for it to show up on a jsp somewhere. Details of these functions are discussed in the Persisting Tainted Data section of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30495</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30495"/>
				<updated>2008-06-05T17:10:42Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Security Implications */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
These issues are discussed in context on this page and are also listed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Important this section] of Hibernate Guidelines.&lt;br /&gt;
&lt;br /&gt;
* No communication with the database can occur outside of a database transaction. Doing so will probably result in synchronization issues. Transactions should also not encompass user think time.&lt;br /&gt;
&lt;br /&gt;
        Details are of how it's done is discussed in the Defining Transaction Bounds section of this page.&lt;br /&gt;
&lt;br /&gt;
        NOTE: An application that has CMT (container-managed-transactions), then transaction demarcation is taken care of and this is irrelevant see section 11.2 of the reference manual.&lt;br /&gt;
&lt;br /&gt;
* 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 SQLQuerys setParameter(), setString(), setXXX() methods for named parameter and placeholder binding. Just like prepared stmts.&lt;br /&gt;
&lt;br /&gt;
        Details are discussed in the Creating Queries section of this page.&lt;br /&gt;
&lt;br /&gt;
* Persisting tainted objects == stored xss. Will need to flag all saves, updates etc. made with an object whose properties were set with tainted data. There is a good chance it will be accessed and displayed at some point. The prospect of writing a scan that detects tainted data coming out of a database is unlikely, so unless someone wants to take a whack at it, flag the functions that make tainted objects persistent in the first place. There are no defining factors for classes of persistent objects (i.e no specific interface/parent/contract), which means it'll be pretty hard to write a scan that finds them. But the .hbm.xml files will tell you which ones they are. Note that 90% of the time these objects will have JavaBeans? Style setters we can ID as propagators.&lt;br /&gt;
&lt;br /&gt;
        Details of these functions are discussed in the Persisting Tainted Data section of this page.&lt;br /&gt;
&lt;br /&gt;
* 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. &lt;br /&gt;
&lt;br /&gt;
* You may not mix and match JDBC-style parameters (&amp;quot;?&amp;quot;) and named parameters (:namedparam) in the same query. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select :somenamedparameter from ? where x = :someothernamedparameter&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
* Transaction.setTimeout(int) should be called to ensure that misbehaving transactions do not tie up resources in definitely. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session sess = factory.openSession();&lt;br /&gt;
     try {&lt;br /&gt;
          //set transaction timeout to 3 seconds&lt;br /&gt;
          sess.getTransaction().setTimeout(3);&lt;br /&gt;
          sess.getTransaction().begin();&lt;br /&gt;
          // do some work&lt;br /&gt;
         ...&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30494</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30494"/>
				<updated>2008-06-05T17:08:03Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
== Headline text ==&lt;br /&gt;
&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Security Implications ==&lt;br /&gt;
&lt;br /&gt;
== Defining Transaction Bounds ==&lt;br /&gt;
&lt;br /&gt;
== Creating, manipulating and executing queries ==&lt;br /&gt;
&lt;br /&gt;
== Persisting tainted data ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30493</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30493"/>
				<updated>2008-06-05T17:05:41Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Hitting the database */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30492</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30492"/>
				<updated>2008-06-05T17:04:53Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Hitting the database */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
''Ok, why don't we just see what it looks like.''&lt;br /&gt;
Example1&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
         Session sess = factory.openSession();&lt;br /&gt;
         Transaction tx;&lt;br /&gt;
         try {&lt;br /&gt;
              tx = sess.beginTransaction();&lt;br /&gt;
              Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
              q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
              tx.commit();&lt;br /&gt;
         }&lt;br /&gt;
         catch (Exception e) {&lt;br /&gt;
             if (tx!=null) tx.rollback();&lt;br /&gt;
             throw e;&lt;br /&gt;
         }&lt;br /&gt;
         finally {&lt;br /&gt;
             sess.close();&lt;br /&gt;
         }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''Another simple example using HQL and named parameters...this time we have a helper class to obtain a Session''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();&lt;br /&gt;
        session.beginTransaction(); //All database communication occurs within the scope of a transaction&lt;br /&gt;
&lt;br /&gt;
        Person aPerson = (Person) session&lt;br /&gt;
                .createQuery(&amp;quot;select p from Person p left join fetch p.events where p.id = :pid&amp;quot;)&lt;br /&gt;
                .setParameter(&amp;quot;pid&amp;quot;, personId); &lt;br /&gt;
&lt;br /&gt;
        session.getTransaction().commit();&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
''An application should instantiate a SessionFactory somewhere outside the scope of the request, conversation, unit of work...Here is a snip of HibernateUtil?.java''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
                                  .......&lt;br /&gt;
            private static final SessionFactory sessionFactory;&lt;br /&gt;
            static {&lt;br /&gt;
                    sessionFactory = new Configuration().configure().buildSessionFactory();&lt;br /&gt;
            }&lt;br /&gt;
            public static SessionFactory getSessionFactory() {&lt;br /&gt;
                return sessionFactory;&lt;br /&gt;
            }                        .......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30491</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30491"/>
				<updated>2008-06-05T17:02:31Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Hitting the database */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30490</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30490"/>
				<updated>2008-06-05T17:02:12Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Hitting the database */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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(). &lt;br /&gt;
&lt;br /&gt;
Anyways, a Session is NOT thread safe and there are associated concurrency issues discussed in [https://www.owasp.org/index.php/Hibernate-Guidelines#Session_and_Concurrency_issues 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().  &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30489</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30489"/>
				<updated>2008-06-05T16:51:16Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Hitting the database ===&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30488</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30488"/>
				<updated>2008-06-05T16:48:41Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Nutshell */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== How it works ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30486</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30486"/>
				<updated>2008-06-05T16:47:16Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Le Nutshell */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Nutshell ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30485</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30485"/>
				<updated>2008-06-05T16:44:05Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Le Nutshell */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/JavaBean JavaBeans] style [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30484</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30484"/>
				<updated>2008-06-05T16:42:47Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Le Nutshell */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; 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.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30483</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30483"/>
				<updated>2008-06-05T16:41:33Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Le Nutshell */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Usually Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file, usually with the default extension .hbm.xml, you will see this mapping in the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* *.hbm.xml 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.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30482</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30482"/>
				<updated>2008-06-05T16:38:55Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* A note about SQL injection */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30481</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30481"/>
				<updated>2008-06-05T16:38:37Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* The problem Hibernate addresses */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
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).&lt;br /&gt;
But many databases can only store and manipulate scalar values organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30480</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30480"/>
				<updated>2008-06-05T16:37:48Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* The problem Hibernate addresses */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30479</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30479"/>
				<updated>2008-06-05T16:36:47Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Architecture Overview */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
* But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30478</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30478"/>
				<updated>2008-06-05T16:32:37Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Status */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30477</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30477"/>
				<updated>2008-06-05T16:31:45Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30476</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30476"/>
				<updated>2008-06-05T16:31:05Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Don't use load() to determine existence */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30475</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30475"/>
				<updated>2008-06-05T16:30:47Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Status ==&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30474</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30474"/>
				<updated>2008-06-05T16:27:48Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Consider externalising query strings */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30473</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30473"/>
				<updated>2008-06-05T16:27:11Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Using Detached Objects */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30472</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30472"/>
				<updated>2008-06-05T16:26:06Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* The equals() and hashCode() problem: */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30471</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30471"/>
				<updated>2008-06-05T16:25:42Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Session and Concurrency issues */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30470</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30470"/>
				<updated>2008-06-05T16:25:21Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Aboot POJOs */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30469</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30469"/>
				<updated>2008-06-05T16:24:32Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* About StatelessSession */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30468</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30468"/>
				<updated>2008-06-05T16:24:05Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Cache Management and !OutOfMemoryException */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30467</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30467"/>
				<updated>2008-06-05T16:23:28Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Don't use session.find() */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30466</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30466"/>
				<updated>2008-06-05T16:22:59Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Parameter Binding */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30465</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30465"/>
				<updated>2008-06-05T16:22:31Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Identify natural keys */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30464</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30464"/>
				<updated>2008-06-05T16:21:56Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Transaction Timeout */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
 - Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
 - A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
 - Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
 - We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
 - This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
{{{&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30463</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30463"/>
				<updated>2008-06-05T16:21:38Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Transaction Timeout */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
 - Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
 - A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
 - Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
 - We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
 - This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
{{{&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30462</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30462"/>
				<updated>2008-06-05T16:21:13Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: /* Rollaback! */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollback == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
 - Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
 - Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
 - In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
 - Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
 - A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
 - Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
 - We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
 - This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
{{{&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30461</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=30461"/>
				<updated>2008-06-05T16:20:55Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: New page: = Important = == SQL Injection ==  It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Important =&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
== Transaction Scope == &lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. Although we can't anticipate all design patterns, it would be an easy scan to flag jdbc and hibernate calls outside of transactions in a Hibernate application.&lt;br /&gt;
&lt;br /&gt;
== Persisting Tainted Data ==&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  Long story short - saves, updates, inserts, whatever that are made with tainted objects should be flagged.&lt;br /&gt;
&lt;br /&gt;
== Rollaback! == &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Simple = &lt;br /&gt;
&lt;br /&gt;
== Don't use load() to determine existence ==&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
== Constructing Query Strings ==&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
== Place each class mapping in its own file ==&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
== Use bind variables ==&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
== Load mappings as resources  ==&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
= Detailed =&lt;br /&gt;
&lt;br /&gt;
== Transaction Timeout ==&lt;br /&gt;
 - Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
 - Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
 - In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Identify natural keys ==&lt;br /&gt;
 - Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
 - A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
 - Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
 - We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
 - This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
{{{&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Parameter Binding == &lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
{{{&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Declare identifier properties on persistent classes ==&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Don't use session.find() ==&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== Cache Management and !OutOfMemoryException == &lt;br /&gt;
&lt;br /&gt;
 - The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
 - Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
 - When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
 - Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
 - One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
 - Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
{{{&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
== About StatelessSession ==&lt;br /&gt;
 - A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
 - This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
 - Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
 - The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
{{{&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
}}}&lt;br /&gt;
Example of improper use?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Aboot POJOs ==&lt;br /&gt;
&lt;br /&gt;
 * You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
 * Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
 * It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
}}} &lt;br /&gt;
&lt;br /&gt;
 * Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Session and Concurrency issues == &lt;br /&gt;
&lt;br /&gt;
 - A Session is not thread-safe. &lt;br /&gt;
 - Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
 - If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
 - Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
***YOU NEED EXAMPLES HERE***&lt;br /&gt;
&lt;br /&gt;
== The equals() and hashCode() problem:  ==&lt;br /&gt;
 &lt;br /&gt;
 * Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
 * If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
 * Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
 * However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
 * So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
 * '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Using Detached Objects ==&lt;br /&gt;
 - In a three tiered architecture, consider using detached objects.&lt;br /&gt;
 - When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
 - Use a new session to service each request. &lt;br /&gt;
 - Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
 - the application loads an object in the first session&lt;br /&gt;
 - the object is passed up to the UI tier&lt;br /&gt;
 - some modifications are made to the object&lt;br /&gt;
 - the object is passed back down to the business logic tier&lt;br /&gt;
 - the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Consider externalising query strings ==&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
 - Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
 - You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
{{{&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
}}}&lt;br /&gt;
&lt;br /&gt;
 - Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
 - Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30460</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30460"/>
				<updated>2008-06-05T16:11:56Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Architecture Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
* But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30459</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30459"/>
				<updated>2008-06-05T16:11:39Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Architecture Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
* But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Category name]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30454</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30454"/>
				<updated>2008-06-05T15:57:13Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Architecture Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
* But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;br /&gt;
&lt;br /&gt;
=== Jargon ===&lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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. &lt;br /&gt;
*'''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.&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30450</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30450"/>
				<updated>2008-06-05T15:54:48Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Architecture Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
* But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[http://www.owasp.org/index.php/Hibernate/config-example See this configuration example]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate/config-example&amp;diff=30448</id>
		<title>Hibernate/config-example</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate/config-example&amp;diff=30448"/>
				<updated>2008-06-05T15:53:52Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: New page: '''Person.java''' &amp;lt;pre&amp;gt; package events;  import java.util.*;  public class Person {      private Long id;     private int age;     private String firstname;     private String lastname;   ...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Person.java'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package events;&lt;br /&gt;
&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
&lt;br /&gt;
    private Long id;&lt;br /&gt;
    private int age;&lt;br /&gt;
    private String firstname;&lt;br /&gt;
    private String lastname;&lt;br /&gt;
    private Set emailAddresses = new HashSet();&lt;br /&gt;
    private Set events = new HashSet();&lt;br /&gt;
&lt;br /&gt;
    public Person() {}&lt;br /&gt;
&lt;br /&gt;
    public Long getId() {&lt;br /&gt;
        return id;&lt;br /&gt;
    }&lt;br /&gt;
    public void setId(Long id) {&lt;br /&gt;
        this.id = id;&lt;br /&gt;
    }&lt;br /&gt;
             .....setters and getters for each property etc......&lt;br /&gt;
&lt;br /&gt;
    protected Set getEvents() {&lt;br /&gt;
        return events;&lt;br /&gt;
    }&lt;br /&gt;
    protected void setEvents(Set events) {&lt;br /&gt;
        this.events = events;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
'''person.hbm.xml mapping file for Person.java'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot;?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE hibernate-mapping PUBLIC&lt;br /&gt;
        &amp;quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&amp;quot;&lt;br /&gt;
        &amp;quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;class name=&amp;quot;events.Person&amp;quot; table=&amp;quot;PERSON&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;id name=&amp;quot;id&amp;quot; column=&amp;quot;PERSON_ID&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;generator class=&amp;quot;native&amp;quot;/&amp;gt;&lt;br /&gt;
        &amp;lt;/id&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;age&amp;quot;/&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;firstname&amp;quot;/&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;lastname&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;set name=&amp;quot;events&amp;quot; table=&amp;quot;PERSON_EVENT&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;key column=&amp;quot;PERSON_ID&amp;quot;/&amp;gt;&lt;br /&gt;
            &amp;lt;many-to-many column=&amp;quot;EVENT_ID&amp;quot; class=&amp;quot;events.Event&amp;quot;/&amp;gt;&lt;br /&gt;
        &amp;lt;/set&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
        &amp;lt;set name=&amp;quot;emailAddresses&amp;quot; table=&amp;quot;PERSON_EMAIL_ADDR&amp;quot;&amp;gt;&lt;br /&gt;
            &amp;lt;key column=&amp;quot;PERSON_ID&amp;quot;/&amp;gt;&lt;br /&gt;
            &amp;lt;element type=&amp;quot;string&amp;quot; column=&amp;quot;EMAIL_ADDR&amp;quot;/&amp;gt;&lt;br /&gt;
        &amp;lt;/set&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;/class&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/hibernate-mapping&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
'''hibernate.cfg.xml configuration file.'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version='1.0' encoding='utf-8'?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE hibernate-configuration PUBLIC&lt;br /&gt;
        &amp;quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&amp;quot;&lt;br /&gt;
        &amp;quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;hibernate-configuration&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;session-factory&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- Database connection settings --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;connection.driver_class&amp;quot;&amp;gt;org.hsqldb.jdbcDriver&amp;lt;/property&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;connection.url&amp;quot;&amp;gt;jdbc:hsqldb:hsql://localhost&amp;lt;/property&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;connection.username&amp;quot;&amp;gt;sa&amp;lt;/property&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;connection.password&amp;quot;&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- JDBC connection pool (use the built-in) --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;connection.pool_size&amp;quot;&amp;gt;1&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- SQL dialect --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;dialect&amp;quot;&amp;gt;org.hibernate.dialect.HSQLDialect&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- Enable Hibernate's automatic session context management --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;current_session_context_class&amp;quot;&amp;gt;thread&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- Disable the second-level cache  --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;cache.provider_class&amp;quot;&amp;gt;org.hibernate.cache.NoCacheProvider&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- Echo all executed SQL to stdout --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;show_sql&amp;quot;&amp;gt;true&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;!-- Drop and re-create the database schema on startup --&amp;gt;&lt;br /&gt;
        &amp;lt;property name=&amp;quot;hbm2ddl.auto&amp;quot;&amp;gt;create&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
        &amp;lt;mapping resource=&amp;quot;events/Event.hbm.xml&amp;quot;/&amp;gt;&lt;br /&gt;
        &amp;lt;mapping resource=&amp;quot;events/Person.hbm.xml&amp;quot;/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;/session-factory&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/hibernate-configuration&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30445</id>
		<title>Hibernate</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate&amp;diff=30445"/>
				<updated>2008-06-05T15:46:11Z</updated>
		
		<summary type="html">&lt;p&gt;Tehmina: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
== Before you begin ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== A note about SQL injection ===&lt;br /&gt;
Since it is the hot topic, I will address it now but discuss in detail later.&lt;br /&gt;
* Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please.&lt;br /&gt;
* There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.&lt;br /&gt;
* 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.  &lt;br /&gt;
* StatelessSession?'s insert(), update(), and delete() methods do NOT wait for a call to commit(), they are equated with direct database communication.&lt;br /&gt;
&lt;br /&gt;
== Architecture Overview ==&lt;br /&gt;
&lt;br /&gt;
=== The problem Hibernate addresses ===&lt;br /&gt;
* 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).&lt;br /&gt;
* But many databases can only store and manipulate scalar values such as integers and strings organized in tables.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping See original article. ]&lt;br /&gt;
&lt;br /&gt;
=== Le Nutshell ===&lt;br /&gt;
* Generally Hibernate applications use [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJOs] to represent objects we want to persist in a database.&lt;br /&gt;
* They are usually implemented in the style of [http://en.wikipedia.org/wiki/JavaBean JavaBeans].&lt;br /&gt;
* These objects should have an identifier property (i.e private class variable) used to represent it's primary key value in the database.&lt;br /&gt;
* This identifier will be mapped in a hibernate mapping file which defaults to the extension .hbm.xml, you will see this mapping in later examples with the &amp;lt;id&amp;gt; element.&lt;br /&gt;
* This mapping 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 optional metadata.&lt;br /&gt;
* There are ways to map object properties programmatically, but this will not be covered until I find reason to include.&lt;br /&gt;
* Once objects are mapped, Hibernate provides the mechanism for you to store and access them via org.hibernate.Session and org.hibernate.Transaction objects.&lt;br /&gt;
* 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.&lt;br /&gt;
* The Transaction object often wraps a database transaction, allowing one to begin() transactions, commit() changes, and rollback() to a previous state.&lt;br /&gt;
* Other classes worth mentioning: SessionFactory, TransactionFactory, and Query.&lt;br /&gt;
* Hibernate's main configuration file, extension .cfg.xml, provides basic setup for things like datasource, dialect, mapping files, etc. &lt;br /&gt;
[[http://www.owasp.org/index.php?Hibernate/config-example See this configuration example]]&lt;/div&gt;</summary>
		<author><name>Tehmina</name></author>	</entry>

	</feed>