<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Brim &#187; Hibernate</title>
	<atom:link href="http://www.brimllc.com/category/blog/java/hibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.brimllc.com</link>
	<description>streamlined software development</description>
	<lastBuildDate>Tue, 31 Jan 2012 23:30:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>GRAILS: Execute Raw/Native SQL Queries</title>
		<link>http://www.brimllc.com/2011/01/grails-execute-rawnative-sql-queries/</link>
		<comments>http://www.brimllc.com/2011/01/grails-execute-rawnative-sql-queries/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 19:30:46 +0000</pubDate>
		<dc:creator>tmillhouse</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.brimllc.com/?p=388</guid>
		<description><![CDATA[Although Grails provides a great abstraction on top of hibernate (GORM), it is sometimes necessary to execute raw SQL against the configured data source. An example of when you might want to do this is when you&#8217;d like to execute a query with computed values for reporting purposes. 
For example, say you have an &#8220;events&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Although Grails provides a great abstraction on top of hibernate (GORM), it is sometimes necessary to execute raw SQL against the configured data source. An example of when you might want to do this is when you&#8217;d like to execute a query with computed values for reporting purposes. </p>
<p>For example, say you have an &#8220;events&#8221; table, and you&#8217;d like to chart how many events were created grouped by the entry dates. You could have SQL like such:</p>
<p><code><br />
select substring(event.data_created, 1, 10) as dateCreated, count(event.id) from event where event.date_created > ? group by dateCreated order by event.date_created;<br />
</code></p>
<p>With the above query, you&#8217;ll retrieve the amount of events grouped by the day they occurred. Since you&#8217;re not binding this return data to any entity, its easier (and in my opinion cleaner), to execute this query apart from any hibernate approach (such as a named query). </p>
<p>In your service, define the following:</p>
<p><code><br />
def sessionFactory;<br />
</code></p>
<p>This line will ensure grails will inject the configured hibernate session factory into your service. Now, within your service method, you could write code as such:</p>
<p><code><br />
Session session = sessionFactory.openSession();<br />
		session.doWork new Work() {<br />
					@Override<br />
					public void execute(Connection conn) throws SQLException {<br />
						// execute your statement against the connection<br />
					}<br />
				};<br />
</code></p>
<p>Let me know if you have any better ideas&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.brimllc.com/2011/01/grails-execute-rawnative-sql-queries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hibernate Automatic Dirty Check for Detached Objects</title>
		<link>http://www.brimllc.com/2010/08/hibernate-automatic-dirty-check-for-detached-objects/</link>
		<comments>http://www.brimllc.com/2010/08/hibernate-automatic-dirty-check-for-detached-objects/#comments</comments>
		<pubDate>Thu, 26 Aug 2010 17:11:11 +0000</pubDate>
		<dc:creator>Yagish Sharma</dc:creator>
				<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.brimllc.com/?p=205</guid>
		<description><![CDATA[Per the Hibernate documentation, Hibernate can perform dirty checks only when the objects are loaded and changed in the scope of a single Session. This means we cannot use detached objects, but we must keep our session open for one conversation (multiple http requests) using Managed Sessions, just to get hibernate&#8217;s dirty check. This introduces [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Per the Hibernate documentation, Hibernate can perform dirty checks only when the objects are loaded and changed in the scope of a single Session. This means we cannot use detached objects, but we must keep our session open for one conversation (multiple http requests) using Managed Sessions, just to get hibernate&#8217;s dirty check. This introduces new challenges of storing the Hibernate Session object in HttpSession, which fails if we deploy in a clustered environment, since most of the fields in Hibernate org.hibernate.impl.SessionImpl class are transient. So, how do we get the benefit of using Detached Objects and also get Hibernate&#8217;s automatic dirty checking?</p>
<p>The following is a brief background of how Hibernate does its dirty checking:</p>
<p>Hibernate Session contains a PersistenceContext object, which maintains a cache of all the objects read from the database as a Map. In the same Session, when I read an object from the db and make changes to it, Hibernate compares the objects and triggers the updates when the session is flushed. Every object in the PersistenceContext is called Persistent object. Once the session closes, the PersistenceContext is lost and so is the cached copy. A detached object, when saved, opens a new session containing an empty PersistenceContext, so there is nothing to compare against for the dirty check.</p>
<p>If we have an original cached copy of the Detached Object (a clone saved in HttpSession) and we are able to place that copy in the PersistenceContext somehow, we can get the dirty check to work. Here is how to do it.</p>
<p>Couple of points here, before we start reading the code -</p>
<p>1)  All your domain models have a generic way to expose their primary key. Here I have defined PrimaryKeyAwareDomainModelObject interface, which exposes a method to access the primary key property.</p>
<p>public interface PrimaryKeyAwareDomainModelObject {<br />
public Integer getPrimaryKey();<br />
}</p>
<p>2) You already have the original cached copy of the Detached Object, and have made changes to service layers to pass it to the DAO layer.</p>
<p>3) Also, your Detached Objects are POJO&#8217;s.</p>
<p>4) You are using Spring HibnerateDaoSupport, else you can get the SessionFactory to access the Hibernate Session.</p>
<pre><code>

/*** This class handles adding the cached Detached Object to PersistenceContext of a new Session.

** 1) Get a new session, or the session associated with this transaction from the
* sessionFactory.

*2) Inside the PersistentContext of the session, add the old
* Model object, so hibernate thinks that it was loaded as part of read
* operation in the same session

*3) Copy the changed values from the new Model
* object to the old Model object, since hibernate does identity check on the
* object in the persistenceContext, passing a new Model directly to hibernate
* will not trigger dirty checking, but create issues.

*4) Call usual saveOrUpdate, which will check the object if its dirty before update.
***/

import org.hibernate.EntityMode;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.PersistenceContext;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.Status;
import org.hibernate.impl.SessionImpl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibBeforeUpdateListener&lt;T extends PrimaryKeyAwareDomainModelObject, Q extends HibernateDaoSupport&gt; {

/***
* Before doing a call on saveOrUpdate on hibernate session - fetch the
* session - get the PersistenceContext, and add the oldModelObj - copy the
* modified fields from new modelObj to oldModelObj.
* You can pass SessionFactory directly instead of HibernateDaoSupport
*/
@SuppressWarnings("unchecked")

public T beforeUpdate(T modelObj, T oldModelObj, Q dataAccessor) {

SessionFactory factory = dataAccessor.getSessionFactory();
Session session = factory.getCurrentSession();
// get the PersistenceContext of this session
PersistenceContext persistenceContext = session instanceof SessionImpl ? ((SessionImpl) session).getPersistenceContext(): null;
if (null != persistenceContext) {
addEntityToPersistenceContext(persistenceContext, oldModelObj,(SessionFactoryImplementor) factory);
}
// copy modified values from newModel to oldModel

// I am using Dozer

return (T) DozerUtility.copy(modelObj, oldModelObj);
}

private EntityKey generateKey(T modelObj, SessionFactoryImplementor sessionFactory) {
// EntityKey is the key used in the map of objects stored in
// PersistenceContext  it requires the primary key, defined by the @Id annotation in the model class
// , persister object which is SingleTableEntityPersister class in my case, and our models type, which is POJO
return new EntityKey(modelObj.getPrimaryKey(), sessionFactory.getEntityPersister(modelObj.getClass().getCanonicalName()),EntityMode.POJO);
}

</code>/***
 * Hibernate stores the entities as an EntityEntry inside a IdentityMap, ie.
 * 2 objects are equal, if they reference the same object, rather than
 * Object.equals and hashcode is equal. EntityEntry contains the original
 * object as loaded from the db, plus also its original state as an Object
 * array, called loadedState. This method mimics the same behavior of
 * hibernate internals, and stores the object and its loadedState.
 *
 * @param context
 * @param oldModelObj
 * @param sessionFactory
 */
 private void addEntityToPersistenceContext(PersistenceContext context, T oldModelObj, SessionFactoryImplementor sessionFactory) {
       Map&lt;String, T&gt; allEntitiesMap = new HashMap&lt;String, T&gt;();
       for(T modelObj : getAllEntityObjects(oldModelObj, allEntitiesMap).values()){
                 context.addEntity(modelObj, Status.MANAGED, sessionFactory.getEntityPersister(modelObj.getClass().getCanonicalName())
                                 .getPropertyValues(modelObj, EntityMode.POJO), generateKey(
                                  modelObj, sessionFactory), null, LockMode.READ, true,
                                  sessionFactory.getEntityPersister(modelObj.getClass().getCanonicalName()), false, true);
     }
 }

 /***
 * Make a list of all sub Entity objects instances inside the object,
 * and add them separately
 * @return
 */
 private Map&lt;String, T&gt; getAllEntityObjects(T object, Map&lt;String, T&gt; allEntityObjects){
   // definitely this object will be added to persistence context
   if(!allEntityObjects.containsKey(object.getClass().getCanonicalName())){
            allEntityObjects.put(object.getClass().getCanonicalName(), (T)object);
    }
   // get all the instance variables and check their annotations
   Field[] fields = object.getClass().getDeclaredFields();
   // if no fields (impossible scenario), then just add the object and send it back
    if(fields.length == 0){
     return allEntityObjects;
   }
   for(Field f : fields){
    Class fieldClass = f.getType();
    if(fieldClass.getAnnotation(javax.persistence.Entity.class) != null){
     try{
         f.setAccessible(true);
         Object fieldValue = f.get(object);
        // only add the domain model objects
         if(fieldValue instanceof PrimaryKeyAwareDomainModelObject &amp;&amp; !allEntityObjects.containsKey(fieldClass.getCanonicalName())){
            allEntityObjects.put(fieldClass.getCanonicalName(), (T)fieldValue);
            getAllEntityObjects((T)fieldValue, allEntityObjects);
         }
      }catch(IllegalAccessException ex){
        // do nothing and move to next field
      }
    }
  }
    return allEntityObjects;
 }<code>
}
</code></pre>
<p>And here is how to use it in a DAO -</p>
<pre><code>
public class MyDataAccessorImpl extends
HibernateDaoSupport{

public void update(T modelObj, T oldModelObj) {
PrimaryKeyAwareDomainModelObject modelObjToUpdate = new HibBeforeUpdateListener().beforeUpdate(modelObj, oldModelObj, this);
getHibernateTemplate().saveOrUpdate(modelObjToUpdate);
}

}
</code></pre>
<p>This approach was the most efficient that used Hibernate&#8217;s own public APIs. If anyone else has a similar approach to the same problem, I would love to hear&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.brimllc.com/2010/08/hibernate-automatic-dirty-check-for-detached-objects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hibernate &#8211; Joining multiple tables that don&#8217;t have a mapped relationship</title>
		<link>http://www.brimllc.com/2010/08/hibernate-joining-multiple-tables-that-dont-have-a-mapped-relationship/</link>
		<comments>http://www.brimllc.com/2010/08/hibernate-joining-multiple-tables-that-dont-have-a-mapped-relationship/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 16:27:18 +0000</pubDate>
		<dc:creator>tmillhouse</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.brimllc.com/?p=143</guid>
		<description><![CDATA[Today I was tasked with converting some queries to HQL; however, in one instance, a mapping was not defined. My entities looked something like:
AuditObject
  &#8211; id
  &#8211; value
  &#8211; modifiedBy
  &#8211; updatedBy
UserObject
  &#8211; id
  &#8211; name
In my scenario, the AuditObject&#8217;s modifiedBy value should be the name of the user [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Today I was tasked with converting some queries to HQL; however, in one instance, a mapping was not defined. My entities looked something like:</p>
<p>AuditObject<br />
  &#8211; id<br />
  &#8211; value<br />
  &#8211; modifiedBy<br />
  &#8211; updatedBy</p>
<p>UserObject<br />
  &#8211; id<br />
  &#8211; name</p>
<p>In my scenario, the AuditObject&#8217;s modifiedBy value should be the name of the user who&#8217;s ID is equal to the updatedBy field in the Audit table (I know this is a very strange situation, but I&#8217;ve inherited a legacy system). </p>
<p>The approach I used to solve this was to use a Cartesion/Cross join in HQL. So my HQL looked something similar to:</p>
<pre>
getHibernateTemplate.find("select new AuditObject({...}, user.name) from AuditObject as audit, UserObject as user where audit.id = ? and audit.updatedBy = user.id")
</pre>
<p>This returns me a list of AuditObjects with the modifiedBy property set as the user&#8217;s name. Also notice that I&#8217;m using the data-transfer approach by defining a constructor that takes in all the properties that I want set. This is very convenient, and hibernate creates the correct join syntax for me.</p>
<p>I&#8217;d be interested if any others out there have found other solutions to this problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.brimllc.com/2010/08/hibernate-joining-multiple-tables-that-dont-have-a-mapped-relationship/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Appending &#8220;WITH UR&#8221; to DB2 Hibernate query</title>
		<link>http://www.brimllc.com/2010/07/appending-with-ur-to-db2-hibernate-query/</link>
		<comments>http://www.brimllc.com/2010/07/appending-with-ur-to-db2-hibernate-query/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 18:04:45 +0000</pubDate>
		<dc:creator>tmillhouse</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.brimllc.com/?p=131</guid>
		<description><![CDATA[I ran into this problem today while working at a client, and I thought I could help others out with a bit more information than I was able to find online.
The problem is that my client has a standard to have &#8220;WITH UR&#8221; appended to all SELECT queries. This wasn&#8217;t a problem with Spring JDBC, [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I ran into this problem today while working at a client, and I thought I could help others out with a bit more information than I was able to find online.</p>
<p>The problem is that my client has a standard to have &#8220;WITH UR&#8221; appended to all SELECT queries. This wasn&#8217;t a problem with Spring JDBC, but now with the move to Hibernate, I had to find a way to provide this functionality. Keep in mind that I don&#8217;t have a choice in this standard, so I&#8217;m not arguing if appending &#8220;WITH UR&#8221; is a good approach or not.</p>
<p>Anyway, I came across this link,  <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-3644?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=32665#action_32665">http://opensource.atlassian.com/projects/hibernate/browse/HHH-3644?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=32665#action_32665</a>, which provides a workaround for this very problem. It involves creating a Hibernate interceptor that checks the query before executing, and appending &#8220;WITH UR&#8221; as appropriate. For my case, since I can assume that every SELECT query requires this suffix, the interceptor code looks as follows:</p>
<pre>
public class DB2Interceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(DB2Interceptor.class
			.getName());

	@Override
	public String onPrepareStatement(String str) {

		// Transform the original query into lower case
		String compstr = str.toLowerCase();

		// Check if we're dealing with a simple select statement
		if (compstr.matches("^select.*") &#038;&#038; !compstr.matches(".*for update.*")) {
			if (!compstr.matches(".*with ur.*")) {
				str += " with ur ";

				if (logger.isDebugEnabled()) {
					logger.debug("Appending \"WITH UR\" to query.");
				}
			}
		}
		return str;
	}
}
</pre>
<p>Now you can wire this up in your Spring application context as such:</p>
<pre>
&lt;bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
		&lt;property name="dataSource" ref="dataSource" /&gt;
		&lt;property name="entityInterceptor"&gt;
    		&lt;bean class="com.company.dao.hibernate.DB2Interceptor"/&gt;
  		&lt;/property&gt;
...
</pre>
<p>Since this satisfies my requirement, I&#8217;m leaving the code as-is for my client; however, if you have a need of setting a specific transaction isolation value (as in the case of the link I mentioned previously), I have a better solution than his proposed Hashtable/thread approach.</p>
<p>Instead, create the ThreadUtils class as he has done, but make the TransactionManager class extend ThreadLocal to ensure this is specific to the calling thread. Be sure to remove the thread local after use, and you can even generate the getter/setter code in an aspect. </p>
<p>Since I wasn&#8217;t required to code the ThreadLocal side of things, I left that out; however, if anyway would benefit from seeing some extra code, let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.brimllc.com/2010/07/appending-with-ur-to-db2-hibernate-query/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

