<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>hibernate &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/hibernate/</link>
	<description>Feed of posts on WordPress.com tagged "hibernate"</description>
	<pubDate>Sat, 28 Nov 2009 13:23:26 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Cascade Delete foreign keys using Hibernate hbm2ddl]]></title>
<link>http://deprecatedconsciousness.wordpress.com/2009/11/25/cascade-delete-foreign-keys-using-hibernate-hbm2ddl/</link>
<pubDate>Wed, 25 Nov 2009 13:48:11 +0000</pubDate>
<dc:creator>electrikmonk</dc:creator>
<guid>http://deprecatedconsciousness.wordpress.com/2009/11/25/cascade-delete-foreign-keys-using-hibernate-hbm2ddl/</guid>
<description><![CDATA[Even though I&#8217;ve been working with Hibernate for 3 years now, I&#8217;ve only just run into th]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Even though I&#8217;ve been working with <a href="http://www.hibernate.org">Hibernate</a> for 3 years now, I&#8217;ve only just run into this issue &#8211; most likely because in past projects we&#8217;ve used POJO generations and now, for the first time in a real life project, I&#8217;m using the Schema Export tool.</p>
<p>It turns out that, for some odd reason, when creating foreign keys for OneToMany / ManyToOne relationships, Hibernate completely ignore the @Cascade annotations or the cascade keyword of the join annotation.</p>
<p>For instance, consider the following model:</p>
<pre class="brush: java;">

@Entity
public class Cat {

 @Id
 @GeneratedValue
 @Column
 private Long id;

 @Column
 private String name;

 @OneToMany(mappedBy = &#34;parent&#34;, cascade = {CascadeType.ALL})
 @ForeignKey(name = &#34;FK_KITTEN_PARENT&#34;)
 private List kittens = new ArrayList();

}

@Entity
public class Kitten {

 @Id
 @Column
 @GeneratedValue
 private Long id;

 @ManyToOne(cascade = CascadeType.ALL)
 private Cat parent;

 @Column
 private String name;
}
</pre>
<p>The resulting DDL for these two classes will be:</p>
<pre class="brush: sql;">
create table Cat (id bigint not null auto_increment, name varchar(255), primary key (id)) ENGINE=InnoDB

create table Kitten (id bigint not null auto_increment, name varchar(255), parent_id bigint, primary key (id)) ENGINE=InnoDB

alter table Kitten add index FK_KITTEN_PARENT (parent_id), add constraint FK_KITTEN_PARENT foreign key (parent_id) references Cat (id)
</pre>
<p>This behavior does not seem to be documented anywhere. The Hibernate guys seem to think it&#8217;s natural for people to assume that the CascadeType and @Cascade definitions are not translated into DDL. What Hibernate does, instead of generating DDL, is automatically deleting the children (Kittens, in our case) of a deleted parent, <strong>when you use the <a href="https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html">Criteria API</a></strong>. And what if you happen to use HQL? tough.</p>
<p>Fortunately, there IS a solution. It involves using the not-so-well documented annotation (or XML attribute) <a href="http://docs.jboss.org/hibernate/stable/annotations/api/org/hibernate/annotations/OnDelete.html">@OnDelete</a> on the parent (Cat, in our case) side of the association, thus:</p>
<pre class="brush: java;">
@Entity
public class Cat {

@Id
@GeneratedValue
@Column
private Long id;

@Column
private String name;

@OneToMany(mappedBy = &#34;parent&#34;, cascade = {CascadeType.ALL})
@ForeignKey(name = &#34;FK_KITTEN_PARENT&#34;)
@OnDelete(action = OnDeleteAction.CASCADE)
private List&#60;Kitten&#62; kittens = new ArrayList&#60;Kitten&#62;();
</pre>
<p>This ensures that the foreign key is created with the appropriate <em>on delete cascade</em> clause and allowing you to safely delete your parent entities not worrying about any children that refer to them.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Hibernate Annotations from a beginner's approach]]></title>
<link>http://jpgmr.wordpress.com/2009/11/23/hibernate-annotations-from-a-beginners-approach/</link>
<pubDate>Mon, 23 Nov 2009 17:57:35 +0000</pubDate>
<dc:creator>Patrick Grimard</dc:creator>
<guid>http://jpgmr.wordpress.com/2009/11/23/hibernate-annotations-from-a-beginners-approach/</guid>
<description><![CDATA[Again this is going to be somewhat of a beginner&#8217;s view similar to my previous posts.  The las]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Again this is going to be somewhat of a beginner&#8217;s view similar to my previous posts.  The last couple weeks I&#8217;ve been trying to expand my knowledge into more than just straight Java.  I&#8217;ve been integrating the Spring framework into my projects for a while and I&#8217;ve become addicted to using it.  I&#8217;m even focusing most of my web projects on Spring MVC, but there were some things I still wanted to improve on.  Enter Hibernate.  So far, most of my projects have all been using straight JDBC, which is fine for small projects, but as you get into larger and modular projects, straight JDBC shows it&#8217;s limitations.</p>
<p>To familiarize myself with Hibernate, <a title="Quick introduction to Hibernate to get you up and running within an hour" href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/tutorial.html" target="_blank">I started with the tutorial at Hibernate&#8217;s website</a>.  Having assimilated the basics pretty easily, I moved on to Hibernate Annotations because the less XML configuration I have to write, the better.  Hibernate Annotations does allow you to use both Annotations and the XML mapping file strategy if your needs require it.  The initial tutorial walks you through an Event manager type application.  One of the classes you create is a utility class named HibernateUtil which is responsible for creating your Hibernate SessionFactory.</p>
<p>In the XML mapping version, you would have something like this:</p>
<pre class="brush: java;">
package com.mycompany;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static Log log = LogFactory.getLog ( HibernateUtil.class );
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		SessionFactory sessionFactory = null;

		try {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch ( Throwable e ) {
			if ( log.isErrorEnabled() ) {
				log.error ( &#34;Initial SessionFactory creation failed.&#34;, e );
				throw new ExceptionInInitializerError ( e );
			}
		}

		return sessionFactory;
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}
</pre>
<p>Modifying it for Annotation based mapping was pretty simple.  I won&#8217;t list the changes you need to make to your persisted object class since that&#8217;s easy enough to achieve following the tutorial, but to change the way the SessionFactory instance is created, you simply need to use the AnnotationConfiguration class instead of Configuration.</p>
<pre class="brush: java;">
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
</pre>
<p>My first attempt had resulted in an Exception about not being able to determine the SQL dialect.  The reason for that was because instead of calling configure() on AnnotationConfiguration() first, I was just calling buildSessionFactory() from AnnotationConfiguration().  Since my dialect is defined in hibernate.cfg.xml, I have to call configure() on AnnotationConfiguration() before calling buildSessionFactory().</p>
<p>So for anybody wanting to learn the basics of Hibernate and take advantage of the Annotation based mapping all within an hour, I highly suggest you follow the online tutorial at Hibernate&#8217;s website first, and then <a title="Free sample chapter of Java Persistence with Hibernate from Manning" href="http://www.manning.com/bauer2/chapter2.pdf" target="_blank">follow it up with a look at section 2.2.1 of the free available chapter</a> from Manning to get your feet wet with Hibernate Annotations.</p>
<p>My next step will be using Hibernate in a Spring project.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Software Engineer]]></title>
<link>http://thewalkin.wordpress.com/2009/11/21/software-engineer/</link>
<pubDate>Sat, 21 Nov 2009 00:46:24 +0000</pubDate>
<dc:creator>The Editor</dc:creator>
<guid>http://thewalkin.wordpress.com/2009/11/21/software-engineer/</guid>
<description><![CDATA[Benipal Technologies Location: Bangalore Experience: 4-6 Years Education: Graduates, MCA, M.Sc Skill]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><span style="text-decoration:underline;"><strong>Benipal Technologies</strong></span><br />
Location: Bangalore<br />
Experience: 4-6 Years<br />
Education: Graduates, MCA, M.Sc<br />
Skills: JAVA J2EE, XML, STRUTS, HIBERNATE, SOAP,<br />
WALK IN INTERVIEWS ON SATURDAY, NOV 21 from 12pm – 5 pm and SUNDAY, NOV 22 from 12 pm – 5 pm.</p>
<p>DESIRED CANDIDATE PROFILE:</p>
<p>Must have a Bachelors degree with any specialization. Preference will be given to M.Sc and MCA degrees. Excellent spoken engish is an absolute must with good presentation skills.</p>
<p>Ability to perform under pressure will be a critical factor.</p>
<p>Contact Details:</p>
<p>Benipal Technologies</p>
<p>28 5th Block 4th B Cross Koramangala Industrial Layout Bangalore, India 560095</p>
<p>Tel: 080-3026-8000</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Optimizing the Lucene index with Hibernate Search]]></title>
<link>http://jadimeo.wordpress.com/2009/11/21/optimizing-the-lucene-index-with-hibernate-search/</link>
<pubDate>Sat, 21 Nov 2009 00:21:53 +0000</pubDate>
<dc:creator>jadimeo</dc:creator>
<guid>http://jadimeo.wordpress.com/2009/11/21/optimizing-the-lucene-index-with-hibernate-search/</guid>
<description><![CDATA[Here&#8217;s a small tip I found out while troubleshooting why my JVM was exiting in the middle of o]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Here&#8217;s a small tip I found out while troubleshooting why my JVM was exiting in the middle of optimizing my index.  </p>
<p>I created a utility class to create and close FullTextSessions for me that also created and committed a transaction at the same time for convenience throughout my code.  But this meant that the <code>optimize()</code> method returned while Lucene was still working, thus leaving my index locked even after the JVM exited:</p>
<pre>FullTextSession s = Search.getFullTextSession(factory.openSession());
s.beginTransaction();
s.getSearchFactory().optimize();
s.getTransaction().commit();
s.close();</pre>
<p>To get the method to block until the optimization work is completed, do not create a transaction:</p>
<pre>FullTextSession s = Search.getFullTextSession(factory.openSession());
s.getSearchFactory().optimize();
s.close();</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Linkuri utile despre jsf]]></title>
<link>http://jeemaster.wordpress.com/2009/11/20/linkuri-utile-despre-jsf/</link>
<pubDate>Fri, 20 Nov 2009 20:03:50 +0000</pubDate>
<dc:creator>Edi</dc:creator>
<guid>http://jeemaster.wordpress.com/2009/11/20/linkuri-utile-despre-jsf/</guid>
<description><![CDATA[Cum sa accesezi corect un managed-bean programatic gasesti aici , sper sa nu dispara pagina si sa am]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Cum sa accesezi corect un<em> managed-bean</em> programatic gasesti <a href="http://www.javabeat.net/tips/79-accessing-managed-bean-methods-programmatical.html"> aici </a>, sper sa nu dispara pagina si sa am timp sa o adaug pe plogul meu (care de asemenea sper sa nu pateasca nimic);</p>
<p>Alte informatii despre <span style="color:blue;"> hibernate si JSF</span>, cum sa faci o aplicatie jsf si <em>Hibernate in netBeans</em>, tutorial oficial NetBeans <a href="http://netbeans.org/kb/61/web/hibernate-vwp.html">aici</a>, foarte interesant si util.</p>
<p>Totorial Hibernate in <span style="color:blue;">eclipse</span> intuitiv gasiti <a href="http://www.vaannila.com/hibernate/hibernate-example/hibernate-tools-1.html"> aici </a>.</p>
<p>Acelas exemplu oferit de catre JDeveloper gasiti <a href="http://www.oracle.com/technology/pub/articles/vohra_hibernate.html"> aici </a>. JDeveloper este un IDE dezvoltat de catre cei de la Oracle.</p>
<p>O alta idee de aplicatie JSF si Hibernate gasiti si <a href="http://wiki.apache.org/myfaces/Hibernate_And_MyFaces"> aici </a>.</p>
<p>Un tutorial interesant despre Hibernate gasiti <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html"> aici </a>.</p>
<p>Informatii interesanta despre cum sa golesti o tabela in Hibernate gasesti <a href="https://forum.hibernate.org/viewtopic.php?t=934392">aici</a>.</p>
<p>Un site interesant despre maparile Hibernate gasiti <a href="http://ndpsoftware.com/HibernateMappingCheatSheet.html"> aici </a>. Mi se pare foarte util pt a intelege mai usor si a dezvolta mai rapid o aplicatie.</p>
<p>O versiune unor probleme care implica hibernate si JSF vor fi adaugate mai tarziu pe acest blog.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Hibernate]]></title>
<link>http://papiforpresident.wordpress.com/2009/11/18/hibernate/</link>
<pubDate>Wed, 18 Nov 2009 05:55:30 +0000</pubDate>
<dc:creator>Papi for President</dc:creator>
<guid>http://papiforpresident.wordpress.com/2009/11/18/hibernate/</guid>
<description><![CDATA[I&#8217;ve really been so quiet these days. (And I am sure no one really misses me here in this blog]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I&#8217;ve really been so quiet these days. (And I am sure no one really misses me here in this blog. Hehehe. But if in case there are some people following me here, let me just share that I am a bit busy helping the family move from my place to our very own home in the province.</p>
<p>You see, I was lucky enough to secure a loan a year ago, and now, the house and lot is ready for occupancy. Yeah!</p>
<p>For now, I just wish you all enjoyed the Pacquaio-Cotto match. <em>Sana lang knockout no?</em></p>
<p>I will be back soon.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Testing your Hibernate Annotion Mapping]]></title>
<link>http://devll.wordpress.com/2009/11/17/testing-your-hibernate-annotion-mapping/</link>
<pubDate>Tue, 17 Nov 2009 15:08:45 +0000</pubDate>
<dc:creator>Martin Hofmann</dc:creator>
<guid>http://devll.wordpress.com/2009/11/17/testing-your-hibernate-annotion-mapping/</guid>
<description><![CDATA[To test if I my mappings are correct, I use the following Java Application which uses SchemaExport. ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>To test if I my mappings are correct, I use the following Java Application which uses <code>SchemaExport</code>. It gives me the SQL-statements and executes them against a database.<br />
To protect the production database, you can either set the second parameter of <code>create()</code> to <code>false</code> and/or change the connection string to a test database.<code><br />
configuration.setProperty(Environment.URL, "jdbc:mysql://localhost/test");<br />
</code></p>
<pre class="brush: java;">
package starter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class SchemaTester {

    public static void main(String[] args) throws ClassNotFoundException {
        AnnotationConfiguration configuration = new AnnotationConfiguration();

        List&#60;Class&#62; classes = findClasses(new File(&#34;src/domain&#34;), &#34;domain&#34;);
        for (Class clazz : classes) {
            configuration.addAnnotatedClass(clazz);
        }

        configuration.configure();
        configuration.setProperty(Environment.URL, &#34;jdbc:mysql://localhost/test&#34;);

        SchemaExport schemaExport = new SchemaExport(configuration);
        schemaExport.create(true, true);
        // schemaExport.execute(true, false, false, true); // to see just create statements
    }

    private static List&#60;Class&#62; findClasses(File directory, String packageName)
                                                                throws ClassNotFoundException  {
        List&#60;Class&#62; classes = new ArrayList&#60;Class&#62;();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            System.out.println(file);
            if (file.isDirectory()) {
                if(!file.getName().contains(&#34;.&#34;)) {
                    classes.addAll(findClasses(file, packageName + &#34;.&#34; + file.getName()));
                }
            } else if (file.getName().endsWith(&#34;.java&#34;)) {
                String javaName = file.getName().substring(0, file.getName().length() - &#34;.java&#34;.length());
                classes.add(Class.forName(packageName + '.' + javaName));
            }
        }
        return classes;
    }
}
</pre>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html">Chapter 1. Setting up an annotations project</a></li>
<li><a href="http://snippets.dzone.com/posts/show/4831">Get all classes within a package</a> </li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ClassCastException with SQLQuery and setCacheable(true)]]></title>
<link>http://infram.wordpress.com/2009/11/17/classcastexception-with-sqlquery-and-setcacheabletrue/</link>
<pubDate>Tue, 17 Nov 2009 10:54:15 +0000</pubDate>
<dc:creator>mascha</dc:creator>
<guid>http://infram.wordpress.com/2009/11/17/classcastexception-with-sqlquery-and-setcacheabletrue/</guid>
<description><![CDATA[Today I had to change a hibernate query constructed with the criteria API to a SQL query. The result]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Today I had to change a hibernate query constructed with the criteria API to a SQL query. The result looked like:</p>
<p><code>String sqlQuery = "select count(*) ...";<br />
Session dbSession = getSession();<br />
SQLQuery crit = dbSession.createSQLQuery(sqlQuery);<br />
crit.setCacheable(true);<br />
return (Integer) crit.uniqueResult();</code></p>
<p>The former query was cached and the new one should be too. But I got the following exception:</p>
<p><code> java.lang.ClassCastException: java.math.BigDecimal<br />
at org.hibernate.cache.StandardQueryCache.put(StandardQueryCache.java:83)</code></p>
<p>The following <a href="https://forum.hibernate.org/viewtopic.php?p=2391020">post from hibernate forum</a> helped me to find a solution. The exception is gone after adding the result as a scalar. And the working query looks like:</p>
<p><code>String sqlQuery = "select count(*) as result ...";<br />
Session dbSession = getSession();<br />
SQLQuery crit = dbSession.createSQLQuery(sqlQuery);<br />
crit.addScalar("result", Hibernate.INTEGER);<br />
crit.setCacheable(true);<br />
return (Integer) crit.uniqueResult();</code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Hibernate Sessions in Two Tier Rich Client Applications]]></title>
<link>http://stephanodesign.wordpress.com/2009/11/16/hibernate-sessions-in-two-tier-rich-client-applications/</link>
<pubDate>Mon, 16 Nov 2009 21:34:52 +0000</pubDate>
<dc:creator>Stefan</dc:creator>
<guid>http://stephanodesign.wordpress.com/2009/11/16/hibernate-sessions-in-two-tier-rich-client-applications/</guid>
<description><![CDATA[  One of the most populare articles in this blog so far ist the one about, well: Hibernate Sessions ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2><a title="Hibernate Sessions in Two Tier Rich Client Applications" href="http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/"></a> </h2>
<div>
<p>One of the most populare articles in this blog so far ist the one about, well: <a href="http://blog.schauderhaft.de/2007/12/17/hibernate-sessions-in-fat-client-anwendungen/">Hibernate Sessions in Two Tier Rich Client Applications</a>. Although the original article is writen in german I keep refering to this article, even in english communities. Therefore I decided to break my habit of writing articles in german only and provide a english version which you are reading right now.</p>
<p>This is NOT a direct translation so there might be some differnces in scope, focus and detail.</p>
<p>Everybody working with Java and Databases is probably aware of Hibernate. It is a great solution for mapping a database schema to a object model. It is used in hundreds of applications. So on my current project we decided to use it as well. But big surprise. While Support in the user forum of hibernate is pretty good most of the time we hit one kind of a problem which had no apropriate solution available: How to handle Sessions in a Two Tier Hibernate Application (Swing or SWT typically).</p>
<p>How could such a essential problem be unsolved? Well Rich Client Applications are not hip anymore. Everybody goes for web applications and in that context the session handling is well understood and there is a easy straight forward solution that works in most cases: On each request open a session, do all your work including constructing the result (e.g. JSP) , close the session. But there is no equivalent for a request in a swing application. And since Rich Client Applications are kind of old fashioned nobody bothers to find (and write about) a clean solution for this problem.</p>
<p>We tried a lot of things, starting with the antipattern of a single session per application. This doesn’t work at all for any kind of serious app for the following reasons:</p>
<ul>
<li>No transaction control between different parts of the application. When you flush/commit a session, everything gets flushed. So imagine a application with two open edit frames. The user hits save in one frame and surprise, her half done changes in the other frame get saved as well. Not good.</li>
<li>Memory Leak. The Hibernate Session keeps track of every entity ever loaded by that session. So if you don’t close the session from time to time the session will grow until the application blows up or the whole database is contained in the session. If nothing else this will cause performance issues.</li>
</ul>
<p>Of course if you write a really small simple application this might work, but not for us. As said before we tried a lot of things to solve our problem in the assumption that our requirements are so common that it can’t be hard to find the solution. We were wron. So if the solution to a problem isn’t easy to find, what should be your first step? Wrong (probably)! Your first step should be to exactly identify the problem. In this case this meant: What are the requirements we had? What are the relevant features/limitations of Hibernate? The requirements were:</p>
<ul>
<li>We want Lazy Loading: Lazy Loading is a real powerfull feature whe working with a rich domain model (as we did) especially in a Swing Application. You just display what every attribute you can reach by any kind of object navigation, hibernate will ensure the data is there. Awesome. This was one of the main selling points for Hibernate vs. plain JDBC. So it wasn’t realy an option to loose it.</li>
<li>Different views of the same entity should show the same state. So if you edit an Object the same Object shown in some kind of list-view should show the updated state immediatly.</li>
<li>It should be obvious for the user what is going to be saved when she hits the save button.</li>
<li>The whole mechanism must be fairly easy to use, since the team was growing and not everybody was a hibernate expert. Also lazy loading problems are sometimes hard to debug and fix.</li>
</ul>
<p>The relevant properties of the Hibernate session are</p>
<ul>
<li>For lazy loading to work an entity must be attached to a open session.</li>
<li>A entity wich contains at least one collection (which are well above 50% of our class) can only be attached to one session at a time.</li>
<li>A session keeps a reference to any entity it loads, until the entity get evicted or the session gets closed.</li>
<li>A Hibernate session guarantees to return the same instance everytime a specific entity is requested.</li>
</ul>
<p>If you look at it in this compact form it is rather obvious that you can’t have your cake and eat it too. The automatic refresh in all views of an object would be easily implemented, when there is only one session. But we simply couldn’t do this. So the decision was made that the automatic refresh is (obviously) not as important as clean transactional control plus lazy loading. So we will have more then one session. But which part of the application is using which session? The Hibernate site uses the term ‘Unit-of-Work’. Each unit of work should be contained in its own session. But this is basically back to step one. A request in a webapp ist a unit of work, but where is a unit of work in a rich client app? Imagine this example: The user fires up the application and opens a search dialog resulting in a list of objects. Clearly we are accessing the database, so we just startet a unit of work. Now she double clicks an item in the list. The entity gets opened in a editor, she edits it and hits save. Work commited, transaction closed, unit of work ended. Wow, thats easy, isn’t it? No it isn’t: She clicks on a different item, edits it, saves it. So now we have opened one session and closed two sessions. Not good.</p>
<p>The answer is actually fairly easy once found: Use one session per frame/internal frame/dialog. Modal dialogs use the session of the frame the got starteted from. Background tasks get their own session. The critical point is the transfer of objects from one frame to another. It is tempting to just pass the object but then you have a object from the wrong session in the frame. Instead pass just the Id (the primary key) and use that to load the object in the new session. This approach solved most of our problems nicely.</p>
<p>Most problems? Yes and no. We have some things that we don’t like to much. I think I know how to solve them but I haven’t implemented them yet. So I can’t really promis anything.</p>
<ul>
<li>Instant refresh in other (readonly) views. When editing a object the changed state is not represented in other views of the same object. This could be fixed by a hibernate interceptor or event listener. It would listen for update events, then check if this entity is contained in any other session, check if that session is read only and if so trigger a refresh of that object. We haven’t implemented that simple due to time constraints.</li>
<li>Saving in background. Most of the stuff we do is simple object editing, but on fairly complex object graphs. So saving an object to DB may take some time. Due to the tight integration of Frames and session we can’t easily delegate this work to a background thread. The same is true of lazy loading. In long lists of complex objects scrolling to new cells for the first time might cause some lag, because lazy loading happens in the Event Handling Thread. The first part should be fairly easy to fix:Open a new Session, find the dirty Objects, merge the dirty Objects in the new Session, do a flush of the new session in a background thread. One just has to make sure the background thread uses its own instances, not the same instances as the original frame/session. The lazy loading in background is more difficult to solve. For almost everything in the GUI we use a <a href="http://www.jgoodies.com/index.html">JGoodies</a> PresentationModel and the associated ValueModels, so the swing objects don’t access directly any attributes of our Hibernate entities. These ValueModel could be used to implement a seperation of two differnt threads: The Swing Event Handling Thread on one side and a seperate thread for all the model work, including lazy loading. But this would mean the whole application is split in two threads, instead of the normal aproach of having one main thread and a couple of worker threads for special work. I think it should be feasibly and actually enforces a very strict and clean architecture, and result in a highly responsive gui, but it would also be a lot of (debugging) work and as everybody knows: Concurrency is hard. So we decided that we don’t need it in this application.</li>
</ul>
<p>If you are going to implement this kind of session handling I strongly suggest to use a director/mediator pattern for all your frames. While always a good idea, it becomes important in this case because it gives you a well defined spot to do your session handling. And of course you should be aware of the alternatives:</p>
<ul>
<li>Go with a single long living session. Only feasable with smallish applications</li>
<li>Kick Lazy Loading and close your session after retrieving your objects. This loses many of the interesting benefits hibernate offers.</li>
</ul>
<p>In any case I how this write up shed some light on the issues and helped to make a informed decission.</p>
<p>Source : <a href="http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/">http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/</a></p>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Operacje kaskadowe w Hibernate]]></title>
<link>http://ziobrowski.wordpress.com/2009/11/16/operacje-kaskadowe-w-hibernate/</link>
<pubDate>Mon, 16 Nov 2009 15:18:42 +0000</pubDate>
<dc:creator>bziobrowski</dc:creator>
<guid>http://ziobrowski.wordpress.com/2009/11/16/operacje-kaskadowe-w-hibernate/</guid>
<description><![CDATA[Tym razem pokazuję jak radzić sobie z nieodpowiednimi ustawieniami operacji kaskadowych, jak działa ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Tym razem pokazuję jak radzić sobie z nieodpowiednimi ustawieniami operacji kaskadowych, jak działa ten mechanizm, oraz jak z niego korzystać.</p>
<p><a href="http://ziobrowski.wordpress.com/files/2009/11/operacjekaskadowe.pdf">Operacje kaskadowe w Hibernate</a></p>
<p>PS. Może w końcu zacznę umieszczać treść artykułów bezpośrednio na stronie, ale jak na razie toporny interfejs  edycji wpisów skutecznie mnie zniecęca.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring MVC Tutorial &ndash; Hibernate Integration]]></title>
<link>http://mhimu.wordpress.com/2009/11/16/spring-mvc-tutorial-hibernate-integration/</link>
<pubDate>Mon, 16 Nov 2009 08:44:00 +0000</pubDate>
<dc:creator>mhimu</dc:creator>
<guid>http://mhimu.wordpress.com/2009/11/16/spring-mvc-tutorial-hibernate-integration/</guid>
<description><![CDATA[After a long gap… For introduction to Spring MVC in particular, see Spring MVC Tutorial and Spring M]]></description>
<content:encoded><![CDATA[After a long gap… For introduction to Spring MVC in particular, see Spring MVC Tutorial and Spring M]]></content:encoded>
</item>
<item>
<title><![CDATA[Cài đặt Windows Server 2008]]></title>
<link>http://dvdenglish.wordpress.com/2009/11/15/cai-d%e1%ba%b7t-windows-server-2008/</link>
<pubDate>Sun, 15 Nov 2009 09:00:03 +0000</pubDate>
<dc:creator>thai230293</dc:creator>
<guid>http://dvdenglish.wordpress.com/2009/11/15/cai-d%e1%ba%b7t-windows-server-2008/</guid>
<description><![CDATA[Bài viết sau đây sẽ hướng dẫn các bạn từng bước cài đặt Windows Server 2008, từ quá trình chuẩn bị c]]></description>
<content:encoded><![CDATA[Bài viết sau đây sẽ hướng dẫn các bạn từng bước cài đặt Windows Server 2008, từ quá trình chuẩn bị c]]></content:encoded>
</item>
<item>
<title><![CDATA[Basic Hibernate @OneToOne @PrimaryKeyJoinColumn Example With Maven and MySQL]]></title>
<link>http://devblog.point2.com/2009/11/14/basic-hibernate-onetoone-primarykeyjoincolumn-example-with-maven-and-mysql/</link>
<pubDate>Sat, 14 Nov 2009 15:33:04 +0000</pubDate>
<dc:creator>Damien Gabrielson</dc:creator>
<guid>http://devblog.point2.com/2009/11/14/basic-hibernate-onetoone-primarykeyjoincolumn-example-with-maven-and-mysql/</guid>
<description><![CDATA[Recently we had a story which involved improving one of our data models. The table for the model had]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Recently we had a <a href="http://www.agilemodeling.com/artifacts/userStory.htm">story</a> which involved improving one of our data models. The table for the model had grown quite wide and we wanted to improve normalization and performance. We wanted to move a few columns from our original table (Listing) to a new table with the primary key of the new table (ListingLocation) also being a foreign key to the primary key of the original table, our <a href="http://www.xylax.net/hibernate/onetoone.html">one-to-one relationship</a>. I will try to detail how we accomplished this change using a simplified example. Source code is linked at the bottom of this post.</p>
<p>Here is the entity relationship diagram of the old, single table structure:<br />
<img class="alignnone size-full wp-image-1080" title="ERD-old" src="http://point2blog.wordpress.com/files/2009/11/erd-old.png" alt="Old ER Diagram" width="175" height="98" /><br />
And here is the entity relationship diagram of the new, two table structure:<br />
<img class="alignnone size-full wp-image-1081" title="ERD-new" src="http://point2blog.wordpress.com/files/2009/11/erd-new.png" alt="New ER Diagram" width="377" height="82" /></p>
<p>As you can see, it is a very simple example of a very common relationship in the database. However, what we found when implementing this in <a href="https://www.hibernate.org/">Hibernate</a> was not a simple as I had hoped.</p>
<p>To get started here is the SQL used to represent our new tables:<br />
<code><br />
CREATE TABLE Listing<br />
(<br />
id BIGINT(20) NOT NULL AUTO_INCREMENT,<br />
price DECIMAL(10,2),<br />
PRIMARY KEY (id)<br />
) TYPE = INNODB;</code><br />
<code><br />
CREATE TABLE ListingLocation<br />
(<br />
listingID BIGINT(20) NOT NULL,<br />
address VARCHAR(255),<br />
PRIMARY KEY(listingID),<br />
INDEX (listingID),<br />
FOREIGN KEY (listingID) REFERENCES Listing (id)<br />
) TYPE = INNODB;<br />
</code></p>
<p>I&#8217;ve used MySQL for this example because it is free and easy to setup. InnoDB table types have been because they allow <a href="http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html">foreign keys</a>, which is crucial to this example.</p>
<p>Our old Listing entity was pretty basic; it looked something like this (imports &#38; getters/setters excluded):<br />
<code><br />
@Entity<br />
@Table<br />
public class Listing implements Serializable {<br />
@Id<br />
@GeneratedValue<br />
private long id;<br />
@Column(columnDefinition= "DECIMAL(10,2)")<br />
private double price;<br />
private String address;<br />
...<br />
</code><br />
In this case, creating a new instance of Listing and persisting it is very easy. When we split the entities, it becomes a little more complicated. Here is what our entities looked like after being split:<br />
<code><br />
@Entity<br />
@Table<br />
public class Listing implements Serializable {<br />
@Id<br />
@GeneratedValue<br />
private long id;<br />
@Column(columnDefinition= "DECIMAL(10,2)")<br />
private double price;<br />
@OneToOne<br />
@PrimaryKeyJoinColumn<br />
private ListingLocation listingLocation;<br />
...<br />
</code><br />
and<br />
<code><br />
@Entity<br />
@Table<br />
public class ListingLocation implements Serializable {<br />
@Id<br />
@Column(name = "listingID")<br />
private Long id;<br />
private String address;<br />
...<br />
</code></p>
<p>The differences are not large, but there are a couple important points to note:</p>
<ul>
<li>Adding ListingLocation to Listing with @OneToOne &#38; @PrimaryKeyJoinColumn annotations tells Hibernate the Listing has a one-to-one mapping with ListingLocation by using the Primary Key as the join column.</li>
<li>Adding @Id &#38; @Column(name = &#8220;listingID&#8221;) annotations to our id field in ListingLocation tells Hibernate that id is, well, an ID, but that column should not be called &#8220;id&#8221; in the DB, but &#8220;listingID&#8221; as that will help an observer see the relationship quickly without looking closely at the schema. Also, it is good to note that the @GeneratedValue is not on &#8220;id&#8221; in ListingLocation as it is in Listing as we want to specify exactly what goes in that field.</li>
</ul>
<p>The biggest gripe I have with using the one-to-one relationship is that we can no longer save Listing only. Our REAL Listing entity is far more complex with several relationships, but this was the first one-to-one relationship with Hibernate. Previously we could do something like:<br />
<code><br />
Listing listing = new Listing();<br />
listing.setPrice(price);<br />
listing.setAddress(address);<br />
listing.setFoo(foo); // where foo is a @OneToMany annotated entity<br />
...<br />
<strong>session.save(listing);</strong><br />
</code><br />
Now, we must save Listing and ListingLocation separately like this:<br />
<code><br />
ListingLocation listingLocation = new ListingLocation();<br />
listingLocation.setAddress(address);<br />
Listing listing = new Listing();<br />
listing.setPrice(price);<br />
listing.setListingLocation(listingLocation);<br />
...<br />
<strong>session.save(listing);</strong><br />
if (listing.getListingLocation() != null) {<br />
listing.getListingLocation().setId(listing.getId());<br />
<strong>session.save(listing.getListingLocation()); // save ListingLocation</strong><br />
}<br />
</code></p>
<p>I guess I&#8217;m just a bit spoiled, but I was hoping that this would bit more automatic, as it is with the one-to-many/many-to-one relationships.</p>
<p style="text-align:left;">I have written a small app that uses these two entities and inserts a row into each table, the link is available at the bottom of this post. The config (hibernate.cfg.xml) expects that you have MySQL running on 127.0.0.1 with a DB named &#8216;OneToOneDemo&#8217; with a user named &#8216;root&#8217; and a password of &#8216;password&#8217;; I have included the SQL (Setup-OneToOneDemo.sql) to setup the DB. Just extract the contents of the archive, navigate to the project directory, and from the command line/terminal run:<br />
<code><br />
mvn clean compile exec:java -Dexec.mainClass=com.point2.onetoonedemo.App -e<br />
</code></p>
<p>You should see the following output:<br />
<code><br />
@OneToOne @PrimaryKeyJoinColumn Hibernate Demo<br />
----------------------------------------------<br />
...<br />
Hibernate:<br />
insert into Listing (price) values (?)</code></p>
<p><code>Hibernate:<br />
insert into ListingLocation (address, listingID) values (?, ?)<br />
Saved listing ID: 1<br />
</code></p>
<p><a href="http://www.mediafire.com/file/jjdzjmqmmnm/OneToOneDemo.zip">Download Source Code</a> (12 KB .ZIP)</p>
<p>If you have any questions, comments, or suggestions on how to do better accomplish one-to-one Hibernate mappings, I would love to hear about them. If you have any problems getting the code to compile and/or run, please let me know and I will make the necessary changes. Everything should just work, providing you modify the hibernate config or setup your DB. I had a difficult time finding complete and recent documentation on this subject so I hope this post and the maven project will help.</p>
<p>By: <a href="http://devblog.point2.com/author/dgp2/" target="_blank">Damien Gabrielson</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Developing Web Application using Spring Framework and Hibernate in NetBeans]]></title>
<link>http://szypulski.wordpress.com/2009/11/13/developing-web-application-using-spring-framework-and-hibernate-in-netbeans/</link>
<pubDate>Fri, 13 Nov 2009 22:14:21 +0000</pubDate>
<dc:creator>mszypulski</dc:creator>
<guid>http://szypulski.wordpress.com/2009/11/13/developing-web-application-using-spring-framework-and-hibernate-in-netbeans/</guid>
<description><![CDATA[In this article I am  showing how to apply Hibernate annotations to develop real-world applications.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">In this article I am  showing how to apply Hibernate annotations to develop real-world applications. With the combination of Hibernate annotation and Spring MVC, developers can drastically reduce the time at the configuration level. No more artless mapping files, no more klutzy XDoclet tags &#8211; life becomes so easy! This article describes a step-by-step procedure of how to build, deploy, and run a J2EE-based Web application using the above-mentioned technologies.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Where do the insects go in the winter?]]></title>
<link>http://gerardinebaugh.wordpress.com/2009/11/12/where-do-the-insects-go-in-the-winter/</link>
<pubDate>Thu, 12 Nov 2009 20:18:57 +0000</pubDate>
<dc:creator>gbaugh</dc:creator>
<guid>http://gerardinebaugh.wordpress.com/2009/11/12/where-do-the-insects-go-in-the-winter/</guid>
<description><![CDATA[Sun is shining! I put on my bright orange, stylish coat and went out for a walk,&#8230; and to get t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h3><a href="http://en.wikipedia.org/wiki/File:IC_Pyrrharctia_isabella_caterpillar.JPG"><img class="alignleft size-full wp-image-262" title="800px-IC_Pyrrharctia_isabella_caterpillar" src="http://gerardinebaugh.wordpress.com/files/2009/11/800px-ic_pyrrharctia_isabella_caterpillar.jpg" alt="800px-IC_Pyrrharctia_isabella_caterpillar" width="350" height="170" /></a>Sun is shining! I put on my bright orange, stylish coat and went out for a walk,&#8230; and to get the mail.</h3>
<h3>    I was surprised that there were still a few crickets, and frogs chirping away in the trees and dried grass. I nearly stepped on a few stray grasshoppers. With the weather in the upper twenties last night, they should all have hibernated for the winter, or laid their eggs, larvae, nymphs or pupae.</h3>
<h3>     The bees and wasps have died off. Well, at least the males and the workers. The females crawl into someplace safe, at least they hope so, until spring.</h3>
<h3>     All my beautiful Monarchs have flown off to far away places to return again in spring.</h3>
<h3>     I have been trying to vacuum up and squish all the Japanese beetles and box elders that have been invading my house for the past month. I know that no matter how vigilant I am at removing them, some will have crawled in-between the siding, or find places under the tiles. Others have gotten inside the house hoping to hold out for spring.</h3>
<h3>     In the middle of winter when the sun beats down on the roof, I will find a fly or a beetle that has a death wish by drowning my morning coffee.</h3>
<h3>    Some caterpillars hibernate, like the woolly bear caterpillar.  That little bugger is not fun to pick up; I try to avoid it altogether. But, every year I make a mistake and touch it, either with my toes, or while grabbing a hand full of weeds. The sharp, stinging sensation is not a pleasant experience, and they seem to be everywhere in the late summer, early fall.</h3>
<h3>     I try not to disturbed any insects as they settle in for the winter; except for the ones in my house. The others, the ones in rotting logs and in the wooded area hidden under leaves, I leave them be. In spring I want to see them flying and diving around flowers. I want the bees to pollinate my flowers. I want to hear the summer songs of the crickets and cicadas and katydids.</h3>
<h3>    For now, as I clean up around the outside of the house. Putting away my rakes, and watering hoses. I hope that all of nature can survive the snows and freezing temperatures.</h3>
<h3>    That reminds me I need a pair of winter gloves.</h3>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Here's an idea]]></title>
<link>http://voixdouce.wordpress.com/2009/11/12/heres-an-idea/</link>
<pubDate>Thu, 12 Nov 2009 13:13:29 +0000</pubDate>
<dc:creator>angelcel</dc:creator>
<guid>http://voixdouce.wordpress.com/2009/11/12/heres-an-idea/</guid>
<description><![CDATA[What&#8217;s with this weather? What&#8217;s with my body? I&#8217;m freezing! Where are the curtain]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>What&#8217;s with this weather? What&#8217;s with my body? I&#8217;m <strong>freezing!</strong> Where are the curtains I ordered (in September)? I want my curtains so that I can shut out the weather. I want to cocoon myself in a centrally heated, thick (<strong>heavily</strong> <strong>interlined</strong>) curtained house. No, hang on. Scratch that. Actually I want to hibernate. Yes, that would be better. Why can&#8217;t humans hibernate? Avoid the cold and the damp altogether, avoid S.A.D. syndrome, avoid over-eating starch because it temporarily makes you feel better but leaves you feeling and looking like a little human butterball by the Spring.</p>
<p>Wake me up when it&#8217;s Spring, would you?</p>
<p style="text-align:center;"><img class="aligncenter size-full wp-image-4228" title="dreamy-doormouse" src="http://voixdouce.wordpress.com/files/2009/11/dreamy-doormouse.jpg" alt="dreamy-doormouse" width="450" height="431" /></p>
<p><a href="http://www.dailymail.co.uk/sciencetech/article-1141364/Enjoying-nap-petal-Even-photo-shoot-doesnt-wake-Dreamy-dormouse.html">Photo from the Daily Mail online</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Here's an idea]]></title>
<link>http://angelcel.wordpress.com/2009/11/12/heres-an-idea/</link>
<pubDate>Thu, 12 Nov 2009 13:10:37 +0000</pubDate>
<dc:creator>angelcel</dc:creator>
<guid>http://angelcel.wordpress.com/2009/11/12/heres-an-idea/</guid>
<description><![CDATA[What&#8217;s with this weather?  What&#8217;s with my body?  I&#8217;m freezing!   Where are the cur]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>What&#8217;s with this weather?  What&#8217;s with my body?  I&#8217;m <strong>freezing</strong>!   Where are the curtains I ordered (in September)?  I want my curtains so that I can shut out the weather. I want to cocoon myself in a centrally heated, thick (<strong>heavily</strong> <strong>interlined</strong>) curtained house. No, hang on.  Scratch that.  Actually I want to hibernate. Yes, that would be better. Why can&#8217;t humans hibernate?  Avoid the cold and the damp altogether, avoid S.A.D. syndrome, avoid over-eating starch because it temporarily makes you feel better but leaves you feeling and looking like a little human butterball by the Spring. </p>
<p>Wake me up when it&#8217;s Spring, would you?</p>
<p style="text-align:center;"><img class="aligncenter size-full wp-image-4175" title="dreamy-doormouse" src="http://angelcel.wordpress.com/files/2009/11/dreamy-doormouse2.jpg" alt="dreamy-doormouse" width="450" height="431" /></p>
<p><a href="http://www.dailymail.co.uk/sciencetech/article-1141364/Enjoying-nap-petal-Even-photo-shoot-doesnt-wake-Dreamy-dormouse.html">Photo from the Daily Mail online</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Problema com múltiplos joins em Criteria]]></title>
<link>http://ggarnier.wordpress.com/2009/11/12/problema-com-multiplos-joins-em-criteria/</link>
<pubDate>Thu, 12 Nov 2009 09:57:10 +0000</pubDate>
<dc:creator>ggarnier</dc:creator>
<guid>http://ggarnier.wordpress.com/2009/11/12/problema-com-multiplos-joins-em-criteria/</guid>
<description><![CDATA[O Criteria é uma API do Hibernate que facilita muito quando precisamos montar uma query complexa com]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>O <a href="https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html">Criteria</a> é uma API do <a href="https://www.hibernate.org/">Hibernate</a> que facilita muito quando precisamos montar uma query complexa com filtros opcionais. Adicionar restrições ou criar joins com esta API é muito mais simples de gerenciar do que concatenando Strings, como faríamos ao trabalhar com SQL puro.</p>
<p>Apesar das vantagens, o Criteria também tem alguns problemas. O último que encontrei foi ao tentar fazer 2 joins entre as mesmas 2 tabelas. No meu caso, eu tinha no banco as tabelas <em>projeto</em> e <em>historico</em>. A segunda tabela é populada através de uma trigger no banco: sempre que o status do projeto muda, a tabela <em>historico</em> registra o status anterior do projeto com data/hora da mudança. Eu precisava fazer uma query que buscasse um projeto com status &#8220;iniciado&#8221; num determinado período de datas e com status &#8220;finalizado&#8221; em outro período. Inicialmente, pensei simplesmente em criar 2 joins entre as tabelas, cada um com um alias diferente e filtrando pelas datas específicas:</p>
<pre class="brush: java;">
Criteria criteria = getSession().createCriteria(Projeto.class);

// Primeiro join
criteria.createCriteria(&#34;historicoList&#34;, &#34;historicoIniciado&#34;, Criteria.LEFT_JOIN)
        .add(Restrictions.eq(&#34;historicoIniciado.status&#34;, Status.INICIADO.value()))
        .add(Restrictions.ge(&#34;historicoIniciado.data&#34;, dataIniciadoDe))
        .add(Restrictions.le(&#34;historicoIniciado.data&#34;, dataIniciadoAte));

// Segundo join
criteria.createCriteria(&#34;historicoList&#34;, &#34;historicoFinalizado&#34;, Criteria.LEFT_JOIN)
        .add(Restrictions.eq(&#34;historicoFinalizado.status&#34;, Status.FINALIZADO.value()))
        .add(Restrictions.ge(&#34;historicoFinalizado.data&#34;, dataFinalizadoDe))
        .add(Restrictions.le(&#34;historicoFinalizado.data&#34;, dataFinalizadoAte));
</pre>
<p>O código acima, apesar de semelhante ao que eu já havia criado para adicionar outros filtros à query de projetos, fazendo joins com outras tabelas, não funcionava. Tentei retirar um dos joins com a tabela <em>historico</em> e funcionou. Ou seja, o problema estava na criação do segundo join com as mesmas tabelas, mesmo utilizando aliases diferentes. Ao pesquisar este problema, descobri que não é um bug. Na verdade, o <a href="http://opensource.atlassian.com/projects/hibernate/browse/HB-555?focusedCommentId=11570&#38;page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_11570">Criteria não suporta múltiplos joins para a mesma associação</a>.</p>
<p>Sendo assim, a solução que encontrei para este problema foi criar uma subquery para a tabela <em>historico</em>, utilizando um <a href="https://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/DetachedCriteria.html">DetachedCriteria</a>:</p>
<pre class="brush: java;">
DetachedCriteria historicoCriteria = DetachedCriteria.forClass(Historico.class, &#34;historicoIniciado&#34;)
        .setProjection(Projections.distinct(Projections.property(&#34;projeto&#34;)))
        .add(Restrictions.eq(&#34;historicoIniciado.status&#34;, Status.INICIADO.value()));
        .add(Restrictions.ge(&#34;historicoIniciado.data&#34;, dataIniciadoDe));
        .add(Restrictions.le(&#34;historicoIniciado.data&#34;, dataIniciadoAte));
criteria.add(Subqueries.propertyIn(&#34;id&#34;, historicoCriteria));
</pre>
<p>Desta forma, apenas um dos joins precisa ser substituído por uma subquery. O outro join pode ser mantido sem problemas.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[IBatis vs Hibernate]]></title>
<link>http://budigunawan.wordpress.com/2009/11/10/ibatis-vs-hibernate/</link>
<pubDate>Tue, 10 Nov 2009 12:24:23 +0000</pubDate>
<dc:creator>Budi Gunawan Kusuma</dc:creator>
<guid>http://budigunawan.wordpress.com/2009/11/10/ibatis-vs-hibernate/</guid>
<description><![CDATA[Sumber : http://www.developersbook.com Hibernate Vs. iBatis? Hibernate or iBatis or both ? Which is ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Sumber : <a href="http://www.developersbook.com/articles/hibernate/Hibernate-Vs-iBatis.php">http://www.developersbook.com</a></p>
<p><strong>Hibernate Vs. iBatis?<br />
Hibernate or iBatis  or both ? Which is better?<br />
Which one to use and when?</strong></p>
<p>These are the few questions that continuously get  asked in most of forums.<br />
What’s really difference between two and really more  importantly when should I use one over the other. Its pretty interesting  question because there are major differences between <a href="http://ibatis.apache.org/">iBatis</a> and <a href="http://www.hibernate.org/">Hibernate</a>.</p>
<p>Within in the java persistence there is no one  size, fits all solution. So, in this case Hibernate which is a de facto standard  is used in lot of places.</p>
<p><!--more-->Let us consider a scenario where Hibernate work  great for initial model. Now Suddenly if you are using stored procedures, well  we can do it in Hibernate but its little difficult; ok we map those, all of  sudden we got some reporting type of queries, those don’t have keys have group  bys; with some difficulty here we can use name queries and stuff like that, but  now starts getting more complicated, we have complex joins, yes you can do in  hibernate, but we can’t do with average developer. We have sql that just doesn’t  work.</p>
<table cellspacing="0" cellpadding="0" width="336" align="right" bgcolor="#fafafa">
<tbody>
<tr>
<td>//<br />
 //  <ins><ins></ins></ins></td>
</tr>
</tbody>
</table>
<p>So these are some of the complexities. One of the  other things I find is, if am looking at an application that doesn’t work very  well with an ORM, aside from these considerations of using stored procedures,  already using SQL, complex joins. In other words, Hibernate works very well if  your data model is well in sync with object model, because ORM solutions like  Hibernate map object to tables. However, let’s suppose data model is not in sync  with object model, in this case you have do lot of additional coding and  complexities are entering into your application, start coming the beyond the  benefits of ORM. So, again all of sudden you are noticing that the flow is gone;  our application is becoming very very complex and developers can’t maintain the  code.</p>
<p>This is where the model starts breaking down. One  size does not fit all. So this is where I like to use iBatis; as the alternative  solution for these type of situations, iBatis maps results sets to objects, so  no need to care about table structures. This works very well for stored  procedures, works very well for reporting applications, etc,.</p>
<table cellspacing="0" cellpadding="0" width="336" align="left" bgcolor="#fafafa">
<tbody>
<tr>
<td>//<br />
 //  <ins><ins></ins></ins></td>
</tr>
</tbody>
</table>
<p>Now the question is , does it work well for  simple CRUD applications? Well, it works because what we have to write is sql.  Then why not use Hibernate for that?</p>
<p>You can start see Some of the decision criteria  that comes into play. So one of the other follow on questions that typically get  is , can I use both? That’s really interesting question! because the answer is  sure.</p>
<p>But,such a thing will never ever exists is java  persistence world. However we can kind of use both to create this little hybrid.  So think of this kind scenario, we have very large application where Hibernate  is working very well for it, but we have a reporting piece that just is a real  nag , its query only , so we can do is, we can use iBatis to pull up the queries  for reporting piece and still use Hibernate for all the operational stuff and  updates. This model actually works well, it doesn’t break the transactional  model, and it doesn’t affect any of the primary &#38; secondary caches with a  Hibernate. It’s a good solution.</p>
<ul>
<li><strong>Use iBatis if</strong>
<ul>
<li>You want to create your own SQL&#8217;s and are willing to maintain them</li>
<li>your environment is driven by relational data model</li>
<li>you have to work existing and complex schema&#8217;s</li>
</ul>
</li>
<li><strong>Use Hibernate if</strong>
<ul>
<li>your environment is driven by object model and wants generates SQL  automatically</li>
</ul>
</li>
</ul>
<p>&#160;</p>
<p><strong>The message is,</strong></p>
<ul>
<li>One size does not fit all the java persistence and the important to know  there are other solutions besides the traditional ORMs, and that would be  iBatis.</li>
<li>Both the solutions work well, given their specific domain.</li>
<li>Look for the opportunity where you can use both.</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[h]]></title>
<link>http://befunkyone.wordpress.com/2009/11/10/h/</link>
<pubDate>Tue, 10 Nov 2009 09:09:52 +0000</pubDate>
<dc:creator>befunkyone</dc:creator>
<guid>http://befunkyone.wordpress.com/2009/11/10/h/</guid>
<description><![CDATA[h]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>h</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Hibernate: Uma introdução ao framework de persistência java]]></title>
<link>http://fabiozoroastro.wordpress.com/2009/11/09/hibernate-uma-introducao-ao-framework-de-persistencia-java/</link>
<pubDate>Mon, 09 Nov 2009 00:29:16 +0000</pubDate>
<dc:creator>fabiozoroastro</dc:creator>
<guid>http://fabiozoroastro.wordpress.com/2009/11/09/hibernate-uma-introducao-ao-framework-de-persistencia-java/</guid>
<description><![CDATA[Olá turma. Hoje eu vou postar no meu blog uma apresentação que fiz sobre o framework de persistência]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá turma. Hoje eu vou postar no meu blog uma apresentação que fiz sobre o framework de persistência de dados java, Hibernate. É uma apresentação de introdução ao framework e creio que tenha ficado bem simples e de fácil entendimento. Clique neste <a href="http://www.zastrotecnologia.com.br/publico/artigos/apresentacao-hibernate.ppt">link</a> para fazer o donwload.</p>
<p>Obrigado e até mais.</p>
<p>PS1: Ah, FeedBacks são sempre bem vindos.</p>
<p>PS2: Caso você encontre o link quebrado, me mande um e-mail: fabiozoroastro@gmail.com</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Automatyczne pobieranie obiektów w hibernate]]></title>
<link>http://ziobrowski.wordpress.com/2009/11/06/automatyczne-pobieranie-obiektow-w-hibernate/</link>
<pubDate>Fri, 06 Nov 2009 22:13:16 +0000</pubDate>
<dc:creator>bziobrowski</dc:creator>
<guid>http://ziobrowski.wordpress.com/2009/11/06/automatyczne-pobieranie-obiektow-w-hibernate/</guid>
<description><![CDATA[Jest to pierwszy z serii artykułów, które chciałbym poświęcić narzędziu Hibernate. Staram się w nim ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://ziobrowski.wordpress.com/files/2009/11/hibernate-automatyczne-pobieranie-obiektow.pdf"></a>Jest to pierwszy z serii artykułów, które chciałbym poświęcić narzędziu Hibernate. Staram się w nim odpowiedzieć na pytanie jak konfigurować mapowanie tabel bazodanowych na obiekty, a w szczególności &#8211; czy dany związek między encjami powinien być gorliwy czy leniwy.</p>
<p><a href="../files/2009/11/hibernate-automatyczne-pobieranie-obiektow.pdf">hibernate-automatyczne-pobieranie-obiektow</a></p>
<p>PS: nadchodząca wersja 3.5 ma, według zapowiedzi zespołu Hibernate (<a href="//www.hibernate.org/357.html#A8">https://www.hibernate.org/357.html#A8</a>), wprowadzić &#34;profile pobierania danych&#34;, czyli możliwość definiowania wielu wersji ustawień pobierania obiektów, które można przeglądać w czasie wykonania aplikacji i wybierać ten najbardziej odpowedni do sytuacji. Postaram się zaktualizować artykuł po tym, gdy wersja 3.5 ujrzy światło dzienne.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[HQL Outer Join v.s. Join Fetch.  What am I getting back?]]></title>
<link>http://pragmaticoder.wordpress.com/2009/11/06/hql-outer-join-v-s-join-fetch-what-am-i-getting-back/</link>
<pubDate>Fri, 06 Nov 2009 03:52:54 +0000</pubDate>
<dc:creator>huanchh</dc:creator>
<guid>http://pragmaticoder.wordpress.com/2009/11/06/hql-outer-join-v-s-join-fetch-what-am-i-getting-back/</guid>
<description><![CDATA[I was a bit confused about the differences between HQL outer join v.s. join fetch, its applications ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I was a bit confused about the differences between HQL outer join v.s. join fetch, its applications and type of behind the scene SQL generated.  Hopefully the following example can clarify these concepts somewhat.   Suppose there is a simple parent child relationship between an entity &#8220;artist&#8221; and &#8220;address&#8221;.</p>
<pre class="brush: xml;">

&#60;set table=&#34;ADDRESS&#34;&#62;
</pre>
<p><strong>Scenario 1: No JOIN on collection expressed in HQL, collection mapping has lazy=false</strong></p>
<p>The HQL:</p>
<pre class="brush: sql;">

SELECT artist

from Artist as artist
</pre>
<p><img class="alignnone size-full wp-image-33" title="ScreenHunter_01 Nov. 02 23.06" src="http://pragmaticoder.wordpress.com/files/2009/11/screenhunter_01-nov-02-23-06.jpg" alt="ScreenHunter_01 Nov. 02 23.06" width="450" height="193" /></p>
<p>Result: Address table loaded via a separate query, hibernate loads the &#8220;address&#8221; entity due to the lazy=false mapping to &#8220;address&#8221;</p>
<p><strong>Scenario 2: No JOIN on collection expressed in HQL, mapping has lazy=true</strong></p>
<p>The mapping:</p>
<p>The HQL:</p>
<pre class="brush: sql;">

SELECT artist

from Artist as artist
</pre>
<p><strong> </strong></p>
<p><img class="alignnone size-full wp-image-34" title="ScreenHunter_02 Nov. 02 23.12" src="http://pragmaticoder.wordpress.com/files/2009/11/screenhunter_02-nov-02-23-12.jpg" alt="ScreenHunter_02 Nov. 02 23.12" width="450" height="101" /></p>
<p>Result: Address object not loaded, lazy initialization exception when trying to access address object</p>
<p><strong>Scenario 3: OUTER JOIN in HQL</strong></p>
<p>This is where things start to get confusing for me, in HQL there is a LEFT JOIN as well as a LEFT JOIN FETCH keyword.</p>
<pre class="brush: sql;">

from Artist as artist

LEFT JOIN artist.address
</pre>
<p>The underlying SQL is as expecte, joining both the artist and address tables and returning everything</p>
<p><img class="alignnone size-full wp-image-35" title="ScreenHunter_03 Nov. 02 23.49" src="http://pragmaticoder.wordpress.com/files/2009/11/screenhunter_03-nov-02-23-49.jpg" alt="ScreenHunter_03 Nov. 02 23.49" width="450" height="119" /></p>
<p>Result: returns artist and address as a list of object array, the “artist” entity is located at index 0, “address” entity is at index 1.</p>
<pre class="brush: java;">

List&#60;Object[]&#62; list = artistDAO.findAll();

System.out.println(&#34;got artist size: &#34; + list.size());

for(Object[] result : list)

{

Artist artistResult = (Artist)result[0];

Address addressResult = (Address)result[1];

System.out.println(&#34;got address: &#34; + addressResult.getAddress());

}
</pre>
<p>Note that “address” is mapped as an association of “artist”, whether THAT gets loaded depends on the fetching plan (lazy or not lazy)</p>
<p><strong>Scenario 4: OUTER JOIN in HQL, with projection</strong></p>
<p><strong> </strong></p>
<p>The HQL</p>
<pre class="brush: sql;">

SELECT artist from Artist as artist

LEFT JOIN artist.address
</pre>
<p>The underlying SQL shows that a join is performed, but only the columns from the &#8220;artist&#8221; table is returned</p>
<p><img class="alignnone size-full wp-image-36" title="ScreenHunter_04 Nov. 02 23.56" src="http://pragmaticoder.wordpress.com/files/2009/11/screenhunter_04-nov-02-23-56.jpg" alt="ScreenHunter_04 Nov. 02 23.56" width="450" height="113" /></p>
<p>Result: Due to the projection to only return “artist”, the resulting SQL joins with “address” but doesn’t return it, so the “address” children entity doesn’t get initialized!!</p>
<p>At first I thought by joining “address” I would get “artist” with “address” association fully loaded, but all I am doing is joining the two entities, and then wasting the join by returning only “artist”.</p>
<p>The correct way to have “address” loaded would have been to use an EAGER FETCH such as scenario 5 expressed below.</p>
<p>The useful thing to do with the outer join this way would have been a restriction, such as</p>
<pre class="brush: sql;">
SELECT artist from Artist as artist

LEFT JOIN artist.address as address&#60;strong&#62; &#60;/strong&#62;

WHERE address.streetName like ‘%elm street%’
</pre>
<p><strong>Scenario 5: LEFT JOIN WITH EAGER FETCH in HQL</strong></p>
<p>The LEFT JOIN FETCH key word in HQL essentially overrides fetching strategy from mapping and eagerly fetches the associations.  The difference between this and a LEFT JOIN is that the association is fully initialized and accessible from the parent object.</p>
<pre class="brush: sql;">
from Artist as artist

LEFT JOIN FETCH artist.address
</pre>
<p>Note the underlying SQL is exactly the same as scenario 4, but the way hibernate returns the objects are different (list of &#8220;artist&#8221; object, as supposed to a list of object array).</p>
<p><img class="alignnone size-full wp-image-37" title="ScreenHunter_05 Nov. 03 00.00" src="http://pragmaticoder.wordpress.com/files/2009/11/screenhunter_05-nov-03-00-00.jpg" alt="ScreenHunter_05 Nov. 03 00.00" width="450" height="150" /></p>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:0;width:1px;height:1px;"><!--[if !mso]&#62; &#60;!  v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} --> <!--[endif]--><!--[if gte mso 9]&#62;  Normal 0   false false false         MicrosoftInternetExplorer4  &#60;![endif]--><!--[if gte mso 9]&#62;   &#60;![endif]--><!--  /* Font Definitions */  @font-face 	{font-family:PMingLiU; 	panose-1:2 1 6 1 0 1 1 1 1 1; 	mso-font-alt:新細明體; 	mso-font-charset:136; 	mso-generic-font-family:auto; 	mso-font-format:other; 	mso-font-pitch:variable; 	mso-font-signature:1 134742016 16 0 1048576 0;} @font-face 	{font-family:"\@PMingLiU"; 	panose-1:0 0 0 0 0 0 0 0 0 0; 	mso-font-charset:136; 	mso-generic-font-family:auto; 	mso-font-format:other; 	mso-font-pitch:variable; 	mso-font-signature:1 134742016 16 0 1048576 0;}  /* Style Definitions */  p.MsoNormal, li.MsoNormal, div.MsoNormal 	{mso-style-parent:""; 	margin:0in; 	margin-bottom:.0001pt; 	mso-pagination:widow-orphan; 	font-size:12.0pt; 	font-family:"Times New Roman"; 	mso-fareast-font-family:"Times New Roman"; 	mso-fareast-language:EN-US;} @page Section1 	{size:8.5in 11.0in; 	margin:1.0in 1.25in 1.0in 1.25in; 	mso-header-margin:.5in; 	mso-footer-margin:.5in; 	mso-paper-source:0;} div.Section1 	{page:Section1;} --><!--[if gte mso 10]&#62; &#60;!   /* Style Definitions */  table.MsoNormalTable 	{mso-style-name:表格內文; 	mso-tstyle-rowband-size:0; 	mso-tstyle-colband-size:0; 	mso-style-noshow:yes; 	mso-style-parent:&#34;&#34;; 	mso-padding-alt:0in 5.4pt 0in 5.4pt; 	mso-para-margin:0in; 	mso-para-margin-bottom:.0001pt; 	mso-pagination:widow-orphan; 	font-size:10.0pt; 	font-family:&#34;Times New Roman&#34;; 	mso-fareast-font-family:&#34;Times New Roman&#34;; 	mso-ansi-language:#0400; 	mso-fareast-language:#0400; 	mso-bidi-language:#0400;} --> <!--[endif]--></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">Scenario 1: No JOIN on collection expressed in HQL, collection mapping has lazy=false</span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">&#60;set name=&#8221;address&#8221; table=&#8221;ADDRESS&#8221; lazy=&#8221;false&#8221;&#62;</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">SELECT artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">from Artist as artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"><!--[if gte vml 1]&#62;                    &#60;![endif]--><!--[if !vml]--><img src="/DOCUME%7E1/VICTOR%7E1/LOCALS%7E1/Temp/msohtml1/01/clip_image002.jpg" alt="" width="587" height="252" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">Result: Address table loaded via a separate query</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">Scenario 2: No JOIN on collection expressed in HQL, mapping has lazy=true</span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">&#60;set name=&#8221;address&#8221; table=&#8221;ADDRESS&#8221;&#62;</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">SELECT artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">from Artist as artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;"> </span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"><!--[if gte vml 1]&#62;  &#60;![endif]--><!--[if !vml]--><img src="/DOCUME%7E1/VICTOR%7E1/LOCALS%7E1/Temp/msohtml1/01/clip_image004.jpg" alt="" width="496" height="112" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">Result: Address object not loaded, lazy initialization exception when trying to access address object</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">Scenario 3: OUTER JOIN in HQL</span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">from Artist as artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">LEFT JOIN artist.address</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">List&#60;Object[]&#62; list = artistDAO.findAll();</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">System.</span><em><span style="font-size:10pt;font-family:&#38;">out</span></em><span style="font-size:10pt;font-family:&#38;">.println(</span><span style="font-size:10pt;font-family:&#38;">&#8220;got artist size: &#8220;</span><span style="font-size:10pt;font-family:&#38;"> + list.size());</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">for</span></strong><span style="font-size:10pt;font-family:&#38;">(Object[] <span style="background:yellow none repeat scroll 0 0;">result</span> : list)</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">{</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> Artist artistResult = (Artist)<span style="background:yellow none repeat scroll 0 0;">result</span>[0];</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> Address addressResult = (Address)<span style="background:yellow none repeat scroll 0 0;">result</span>[1];</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> System.</span><em><span style="font-size:10pt;font-family:&#38;">out</span></em><span style="font-size:10pt;font-family:&#38;">.println(</span><span style="font-size:10pt;font-family:&#38;">&#8220;got address: &#8220;</span><span style="font-size:10pt;font-family:&#38;"> + addressResult.getAddress());</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">}</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"><!--[if gte vml 1]&#62;  &#60;![endif]--><!--[if !vml]--><img src="/DOCUME%7E1/VICTOR%7E1/LOCALS%7E1/Temp/msohtml1/01/clip_image006.jpg" alt="" width="561" height="149" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">Result: returns artist and address as a list of object array, the “artist” entity is located at index 0, “address” entity is at index 1. </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">Note that “address” is mapped as an association of “artist”, whether THAT gets loaded depends on the fetching plan (lazy or not lazy)</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">Scenario 4: OUTER JOIN in HQL, with projection</span></strong></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;"> </span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">SELECT artist from Artist as artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">LEFT JOIN artist.address</span><strong><span style="font-size:10pt;font-family:&#38;"> </span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">List&#60;Artist&#62; list = artistDAO.findAll();</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">System.</span><em><span style="font-size:10pt;font-family:&#38;">out</span></em><span style="font-size:10pt;font-family:&#38;">.println(</span><span style="font-size:10pt;font-family:&#38;">&#8220;got artist size: &#8220;</span><span style="font-size:10pt;font-family:&#38;"> + list.size());</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">for</span></strong><span style="font-size:10pt;font-family:&#38;">(Artist <span style="background:yellow none repeat scroll 0 0;">result</span> : list)</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">{</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> System.</span><em><span style="font-size:10pt;font-family:&#38;">out</span></em><span style="font-size:10pt;font-family:&#38;">.println(</span><span style="font-size:10pt;font-family:&#38;">&#8220;got address: &#8220;</span><span style="font-size:10pt;font-family:&#38;"> + <span style="background:yellow none repeat scroll 0 0;">result</span>.getAddress());</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">}</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"><!--[if gte vml 1]&#62;  &#60;![endif]--><!--[if !vml]--><img src="/DOCUME%7E1/VICTOR%7E1/LOCALS%7E1/Temp/msohtml1/01/clip_image008.jpg" alt="" width="550" height="139" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">Result: Due to the projection to only return “artist”, the resulting SQL joins with “address” but doesn’t return it, so the “address” children entity doesn’t get initialized!!</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">At first I thought by joining “address” I would get “artist” with “address” association fully loaded, but all I am doing is joining the two entities, and then wasting the join by returning only “artist”. </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">The correct way to have “address” loaded would have been to use an EAGER FETCH such as scenario 5 expressed below.</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">The useful thing to do with the outer join this way would have been a restriction, such as</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">SELECT artist from Artist as artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">LEFT JOIN artist.address as address</span><strong><span style="font-size:10pt;font-family:&#38;"> </span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">WHERE address.streetName like ‘%elm street%’</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">Scenario 5: LEFT JOIN WITH EAGER FETCH in HQL</span></strong></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">from Artist as artist</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">LEFT JOIN FETCH artist.address</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">List&#60;Artist&#62; list = artistDAO.findAll();</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">System.</span><em><span style="font-size:10pt;font-family:&#38;">out</span></em><span style="font-size:10pt;font-family:&#38;">.println(</span><span style="font-size:10pt;font-family:&#38;">&#8220;got artist size: &#8220;</span><span style="font-size:10pt;font-family:&#38;"> + list.size());</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:&#38;">for</span></strong><span style="font-size:10pt;font-family:&#38;">(Artist result : list)</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">{</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> System.</span><em><span style="font-size:10pt;font-family:&#38;">out</span></em><span style="font-size:10pt;font-family:&#38;">.println(</span><span style="font-size:10pt;font-family:&#38;">&#8220;got address: &#8220;</span><span style="font-size:10pt;font-family:&#38;"> + result.getAddress());</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">}</span><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"><!--[if gte vml 1]&#62;  &#60;![endif]--><!--[if !vml]--><img src="/DOCUME%7E1/VICTOR%7E1/LOCALS%7E1/Temp/msohtml1/01/clip_image010.jpg" alt="" width="521" height="174" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;"> </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:&#38;">Result: the children address is fully initialized, and is accessible via parent; the resulting query returns an artist object</span></p>
</div>
</div>]]></content:encoded>
</item>

</channel>
</rss>
