<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-35989613</id><updated>2011-11-30T03:44:28.464-08:00</updated><category term='bean reference'/><category term='Hibernate best practices'/><category term='hibernate tips'/><category term='hibernate points'/><category term='avoid duplicate'/><category term='spring 3 expression language example'/><category term='preprocess beans'/><category term='HQL fetch'/><category term='resolve password for datasource'/><category term='spring 3 EL'/><category term='outer join'/><category term='refer bean properties in other bean in spring'/><category term='hibernate quick look'/><category term='Bypass lazy initialization in HQL.'/><category term='govind mekala'/><category term='Avoid loading all objects to find count in hibernate.'/><category term='Hibernate guide'/><category term='entities'/><category term='auto scan'/><category term='jpa'/><category term='auto scan jpa entities'/><category term='spring'/><category term='govind'/><category term='avoid duplicate entities from hibernate outer joins'/><category term='Hibernate refresher'/><category term='applicationcontext'/><title type='text'>Spring, JPA, Hibernate Best Practices and Tips</title><subtitle type='html'>This blog is an attempt to provide quick and simple tips to spring, hibernate, and JPA developers. There is so much that can be achieved using spring and JPA, yet sometimes it becomes difficult to find the right information quickly. Hopefully this blog will help some developers in tricky situations.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>10</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-35989613.post-1762774065875640840</id><published>2011-11-16T19:06:00.000-08:00</published><updated>2011-11-16T19:26:35.080-08:00</updated><title type='text'>Using Java Annotation with Spring AOP</title><content type='html'>Here is a short refresher for your&amp;nbsp;spring aop vocabulary.&lt;br /&gt;&lt;br /&gt;"Spring AOP uses &lt;b&gt;Aspect &lt;/b&gt;to &lt;b&gt;Advice &lt;/b&gt;about possible actions with respect to &lt;b&gt;Target &lt;/b&gt;object at the &lt;b&gt;Join Point &lt;/b&gt;matching &lt;b&gt;Point Cut&lt;/b&gt;&amp;nbsp;expression". Aspects are linked to Proxy by run time weaving. Unlike AspectJ, a join point is always a method in Spring.&lt;br /&gt;-----------------------&lt;br /&gt;You can write spring aop advice, which will work based on your custom java annotations. Here is a simple example. Please read about spring aop limitations at the end.&lt;br /&gt;&lt;br /&gt;Define annotation name MethodAnnotation:&lt;br /&gt;&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt; import java.lang.annotation.ElementType;  &lt;br /&gt; import java.lang.annotation.Retention;  &lt;br /&gt; import java.lang.annotation.RetentionPolicy;  &lt;br /&gt; import java.lang.annotation.Target;  &lt;br /&gt; @Retention(RetentionPolicy.RUNTIME)  &lt;br /&gt; @Target(ElementType.METHOD)  &lt;br /&gt; public @interface MethodAnnotation {  &lt;br /&gt;      String comment();  &lt;br /&gt; }  &lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Define Aspect for the annotation. In this example we are using @around advice&lt;br /&gt;&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt; import org.aspectj.lang.ProceedingJoinPoint;  &lt;br /&gt; import org.aspectj.lang.annotation.Around;  &lt;br /&gt; import org.aspectj.lang.annotation.Aspect;  &lt;br /&gt; import org.aspectj.lang.annotation.Pointcut;  &lt;br /&gt; @Component   &lt;br /&gt; @Aspect  &lt;br /&gt; public class AspectForMethodAnnotation{  &lt;br /&gt;      @Around("@annotation(methodAnnotation)")  &lt;br /&gt;      public Object executeAroundMethod(ProceedingJoinPoint pjp, MethodAnnotation methodAnnotation) throws Throwable {  &lt;br /&gt;           // Do what you want with the actionperformed  &lt;br /&gt;           String commentFromAnnotation = methodAnnotation.comment();  &lt;br /&gt;           // You can use join point arguments in any way you like  &lt;br /&gt;           for ( Object object : pjp.getArgs()) {  &lt;br /&gt;                System.out.println(object);  &lt;br /&gt;           }  &lt;br /&gt;           Object ret = pjp.proceed();  &lt;br /&gt;         //doing something after method execution  &lt;br /&gt;         return ret;  &lt;br /&gt;      }  &lt;br /&gt; }  &lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;There are few points to note here. First of all, java annotation will provide method arguments through&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', serif;"&gt;&lt;b&gt;&lt;span class="Apple-style-span" style="background-color: #f0f0f0; line-height: 20px; white-space: pre;"&gt;ProceedingJoinPoint.&lt;/span&gt;&lt;span class="Apple-style-span" style="background-color: white;"&gt;getArgs()&amp;nbsp;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;but not the exact variable name (unless you compile the classes with debug option). So if you have any logic based on&amp;nbsp;argument&amp;nbsp;name, you might want to consider passing index of that&amp;nbsp;argument&amp;nbsp;within annotation. To make auto proxy discover your aspect, you can declare it as @component or @configurable.&lt;br /&gt;&lt;br /&gt;That's all. You can define auto proxy in applicationcontext.xml as below&lt;br /&gt;&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt; &amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;  &lt;br /&gt; &amp;lt;beans xmlns="http://www.springframework.org/schema/beans"  &lt;br /&gt;     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  &lt;br /&gt;     xmlns:aop="http://www.springframework.org/schema/aop"  &lt;br /&gt;     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  &lt;br /&gt;               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"&amp;gt;  &lt;br /&gt; .....  &lt;br /&gt;  &amp;lt;aop:aspectj-autoproxy/&amp;gt;  &lt;br /&gt; &amp;lt;bean id="methodAnnotationAspect" class="com.mdc.spring.annotationexample.AspectForMethofAnnotation" /&amp;gt;  &lt;br /&gt; ......  &lt;br /&gt; &amp;lt;/beans&amp;gt;  &lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;To inject our annotation inside a bean available within spring context, simply add annotation&lt;br /&gt;&lt;pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"&gt;&lt;code style="color: black; word-wrap: normal;"&gt; @MethodAnnotation(comment="World's best method")  &lt;br /&gt; public void bestMethod(String arg1, UrObject arg2) {  &lt;br /&gt; }  &lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;There are some caveats to this approach. If you add multiple annotations within same bean and one method calls another, then spring will not fire aop advice for subsequent calls. This is because sping aop is based on run time proxy. When a proxy invokes method on its instance, consecutive method invocation happens in actual instance, without knowledge of spring environment.&lt;br /&gt;&lt;br /&gt;If you could have annotation class in multiple packages then place full package of annotation interface inside @annotation(...).&lt;br /&gt;&lt;br /&gt;More info and examples of point cuts are in spring doc:&amp;nbsp;&lt;a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-introduction-spring-defn"&gt;http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-introduction-spring-defn&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;47 degrees has extended this concept to implement a dynamic pub-sub functionality.&amp;nbsp;&lt;a href="http://47deg.com/lab/simple-event-with-java-spring-aop-annotations/"&gt;http://47deg.com/lab/simple-event-with-java-spring-aop-annotations/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-1762774065875640840?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/1762774065875640840/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=1762774065875640840&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/1762774065875640840'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/1762774065875640840'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2011/11/using-java-annotation-with-spring-aop.html' title='Using Java Annotation with Spring AOP'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-3720979781497959458</id><published>2011-10-01T09:48:00.000-07:00</published><updated>2011-10-03T22:07:37.409-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='applicationcontext'/><category scheme='http://www.blogger.com/atom/ns#' term='spring 3 expression language example'/><category scheme='http://www.blogger.com/atom/ns#' term='preprocess beans'/><category scheme='http://www.blogger.com/atom/ns#' term='spring 3 EL'/><category scheme='http://www.blogger.com/atom/ns#' term='resolve password for datasource'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='bean reference'/><category scheme='http://www.blogger.com/atom/ns#' term='refer bean properties in other bean in spring'/><title type='text'>Preprocess bean property before assigning to bean in Spring applicationcontext</title><content type='html'>There could be a need to evaluate, validate or pre process a value before assigning as a property in a spring bean. One of the practical use of this technique is to decrypt password before assigning in data source. Spring 3 provides an elegant way to do this without extending any spring class. This is made possible by Expression Language supported by Spring 3 onwards. &lt;br /&gt;&lt;br /&gt;&lt;pre  style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"&gt;&lt;code style="color:#000000;word-wrap:normal;"&gt; &amp;lt;bean id="datasourcePreprocessor" class="com.me.company.Preprocessor"&amp;gt;  &lt;br /&gt;  &amp;lt;property name="inputPassword" value="HighlyEncryptedPassword"/&amp;gt;  &lt;br /&gt;  &amp;lt;property name="user" value="userName"/&amp;gt;   &lt;br /&gt; &amp;lt;!-- other properties --&amp;gt;  &lt;br /&gt;  &amp;lt;/bean&amp;gt;   &lt;br /&gt; &amp;lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&amp;gt;  &lt;br /&gt;  &amp;lt;property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/&amp;gt;   &lt;br /&gt; &amp;lt;property name="url" value="jdbc:oracle:thin:@my.db.server:1521:SID"/&amp;gt;   &lt;br /&gt; &amp;lt;property name="username"value="#{ datasourcePreprocessor.user }"/&amp;gt;   &lt;br /&gt; &amp;lt;property name="password" value="#{ datasourcePreprocessor.outputPassword }"/&amp;gt;  &lt;br /&gt;  &amp;lt;/bean&amp;gt;  &lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;You can implement the decrypt method in setInputPassword  or getOutputPassword() method of com.me.company.Preprocessor.&lt;br /&gt;Anotherside tip of this facility is that you can refer to any system property by simply putting something like value=&amp;quot;#{ systemProperties['user.name'] }&amp;quot;. 'systemProperties' is predefined in spring 3.&lt;br /&gt;&lt;br /&gt;To read more about this technique read &amp;lt;a href=&amp;quot;http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html&amp;quot;&amp;gt;http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html&amp;lt;/a&amp;gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-3720979781497959458?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/3720979781497959458/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=3720979781497959458&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/3720979781497959458'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/3720979781497959458'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2011/10/preprocess-bean-property-before.html' title='Preprocess bean property before assigning to bean in Spring applicationcontext'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-6991081415150868578</id><published>2011-09-26T18:41:00.000-07:00</published><updated>2011-10-03T22:05:47.860-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='applicationcontext'/><category scheme='http://www.blogger.com/atom/ns#' term='avoid duplicate'/><category scheme='http://www.blogger.com/atom/ns#' term='avoid duplicate entities from hibernate outer joins'/><category scheme='http://www.blogger.com/atom/ns#' term='outer join'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate tips'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate best practices'/><title type='text'>How to avoid duplicate entities from hibernate outer join</title><content type='html'>Ever wondered why we get duplicate entities as a result of outer join from Hibernate. We would expect this as hibernate query results should be smart enough to remove duplicates based on primary key (id) field. It does not happen by default. If you run into this issue, you can use DistinctRootEntityResultTransformer. To reduce your result set into distinct entities:&lt;br /&gt;&lt;br /&gt;&lt;pre  style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"&gt;&lt;code style="color:#000000;word-wrap:normal;"&gt; String hql = "from p from Parent p left outer join p.children where c.name=:name";  &lt;br /&gt; Query q = session.createQuery(hql);  &lt;br /&gt; q.setString("name", "John");   &lt;br /&gt; List&amp;lt;parent&amp;gt; parents = (Parent)DistinctRootEntityResultTransformer.transformList(q.list());  &lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;If you are using @OneToMany(fetch=FetchType.EAGER) then "Set" should be used to avoid duplicate entities. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-6991081415150868578?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/6991081415150868578/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=6991081415150868578&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/6991081415150868578'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/6991081415150868578'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2011/09/duplicate-entities-from-hibernate-outer.html' title='How to avoid duplicate entities from hibernate outer join'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-1398392321165022619</id><published>2011-01-26T20:55:00.000-08:00</published><updated>2011-03-26T17:46:49.054-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='entities'/><category scheme='http://www.blogger.com/atom/ns#' term='applicationcontext'/><category scheme='http://www.blogger.com/atom/ns#' term='jpa'/><category scheme='http://www.blogger.com/atom/ns#' term='auto scan'/><category scheme='http://www.blogger.com/atom/ns#' term='spring'/><category scheme='http://www.blogger.com/atom/ns#' term='auto scan jpa entities'/><title type='text'>How to auto scan jpa entities? (using spring configuration)</title><content type='html'>If you configure spring with annotation-config and datasource, spring provides easy way to auto scan entity classes within a package. You can find details of this configuration at &lt;a href="http://weblogs.java.net/blog/2007/11/27/annotation-based-configuration-spring"&gt;http://weblogs.java.net/blog/2007/11/27/annotation-based-configuration-spring&lt;/a&gt;. You might think it should be pretty simple to let spring scan all JPA persistence entitites even when you define EntityManagerFactory instead of DataSource. Well, spring by default scans @Entity classes from same path as persistence.xml. There is no easy way to specify a package name and let spring scan within that package instead of giving relative or absolutely path. Here I tell you steps to achieve the same. It really helps to specify the package scan like you can do with datasource configuration. &lt;b&gt;&lt;u&gt;Step1:&lt;/u&gt;&lt;/b&gt; Define a custom bean say myMagicScanner like this&lt;textarea cols="50" rows="10" &gt;&amp;lt;bean id=&amp;quot;myMagicScanner &amp;quot; class=&amp;quot;com.springjpa.util.MyMagicScanner &amp;gt; &amp;lt;property name=&amp;quot;packageToScan&amp;quot;&amp;gt;  &amp;lt;list&amp;gt;&amp;lt;value&amp;gt;com.springjpa.entities.goodentities&amp;lt;/value&amp;gt;&amp;lt;value&amp;gt;com.springjpa.entities.verygoodentities&amp;lt;/value&amp;gt;  &amp;lt;/list&amp;gt; &amp;lt;/property&amp;gt;&amp;lt;/bean&amp;gt;&lt;/textarea&gt; &lt;br /&gt;&lt;b&gt;&lt;u&gt;Step 2:&lt;/u&gt;&lt;/b&gt; While defining EntityManagerFactory use above bean as PersistenceUnitPostProcessor &lt;br /&gt;Define a custom bean say myMagicScanner like this&lt;textarea cols="50" rows="10" &gt;&amp;lt;bean id=&amp;quot;entityManagerFactory&amp;quot; class=&amp;quot;org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean&amp;quot;&amp;gt; &amp;lt;property name=&amp;quot;persistenceXmlLocation&amp;quot; value=&amp;quot;classpath:META-INF/persistence.xml&amp;quot;/&amp;gt;  &amp;lt;property name=&amp;quot;persistenceUnitName&amp;quot; value=&amp;quot;myPersistenceUnitInPersistenceXML&amp;quot;/&amp;gt;  &amp;lt;property name=&amp;quot;dataSource&amp;quot; ref=&amp;quot;myDataSource&amp;quot;/&amp;gt;  &amp;lt;property name=&amp;quot;jpaVendorAdapter&amp;quot;&amp;gt;  &amp;lt;bean class=&amp;quot;org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter&amp;quot; /&amp;gt; &amp;lt;/property&amp;gt; &amp;lt;property name=&amp;quot;persistenceUnitPostProcessors&amp;quot;&amp;gt;   &amp;lt;list&amp;gt;   &amp;lt;ref bean=&amp;quot;myMagicScanner&amp;quot; /&amp;gt;   &amp;lt;/list&amp;gt;  &amp;lt;/property&amp;gt;&amp;lt;/bean&amp;gt;      &lt;/textarea&gt; &lt;b&gt;&lt;u&gt;Step 3:&lt;/u&gt;&lt;/b&gt;&lt;br/&gt; Finally here is the java class for scanner utility used in MyMagicScannerBean. Notice that I am implementing org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor package com.springjpa.util; &lt;br /&gt;&lt;textarea cols="50" rows="100" wrap="soft"&gt;import java.io.IOException;import java.util.HashSet;import java.util.Set;import javax.persistence.Embeddable;import javax.persistence.Entity;import javax.persistence.MappedSuperclass;import org.hibernate.MappingException;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver;import org.springframework.core.type.classreading.CachingMetadataReaderFactory;import org.springframework.core.type.classreading.MetadataReader;import org.springframework.core.type.classreading.MetadataReaderFactory;import org.springframework.core.type.filter.AnnotationTypeFilter;import org.springframework.core.type.filter.TypeFilter;import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor;import org.springframework.util.ClassUtils;public class MyMagicScanner implements ApplicationContextAware,  PersistenceUnitPostProcessor { private static final String RESOURCE_PATTERN = &amp;quot;**/*.class&amp;quot;; private ApplicationContext applicationContext; private String[] packagesToScan; private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); private TypeFilter[] entityTypeFilters = new TypeFilter[] {   new AnnotationTypeFilter(Entity.class, false),   new AnnotationTypeFilter(Embeddable.class, false),   new AnnotationTypeFilter(MappedSuperclass.class, false) }; @Override public void setApplicationContext(ApplicationContext applicationContext)   throws BeansException {  this.applicationContext = applicationContext; } @Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {  String[] entities = scanPackages();  for (String entity : entities) {   pui.addManagedClassName(entity);  } } /**  *   * Set whether to use Spring-based scanning for entity classes in the  * classpath instead of listing annotated classes explicitly.  *   * &amp;lt;p&amp;gt;  *   * Default is none. Specify packages to search for autodetection of your  * entity classes in the classpath. This is analogous to  *   * Spring's component-scan feature  * (org.springframework.context.annotation.ClassPathBeanDefinitionScanner}).  */ public void setPackagesToScan(String[] packagesToScan) {  this.packagesToScan = packagesToScan; } /**  *   * Perform Spring-based scanning for entity classes.  *   * @see #setPackagesToScan  */ protected String[] scanPackages() {  Set&amp;lt;String&amp;gt; entities = new HashSet&amp;lt;String&amp;gt;();  if (this.packagesToScan != null) {   try {    for (String pkg : this.packagesToScan) {     String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX       + ClassUtils.convertClassNameToResourcePath(pkg)       + RESOURCE_PATTERN;     Resource[] resources = this.resourcePatternResolver       .getResources(pattern);     MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(       this.resourcePatternResolver);     for (Resource resource : resources) {      if (resource.isReadable()) {       MetadataReader reader = readerFactory         .getMetadataReader(resource);       String className = reader.getClassMetadata()         .getClassName();       if (matchesFilter(reader, readerFactory)) {        entities.add(className);       }      }     }    }   } catch (IOException ex) {    throw new MappingException(      &amp;quot;Failed to scan classpath for unlisted classes&amp;quot;, ex);   }  }  return entities.toArray(new String[entities.size()]); } /**  *   * Check whether any of the configured entity type filters matches the  * current class descriptor contained in the metadata  *   * reader.  */ private boolean matchesFilter(MetadataReader reader,   MetadataReaderFactory readerFactory) throws IOException {  if (this.entityTypeFilters != null) {   for (TypeFilter filter : this.entityTypeFilters) {    if (filter.match(reader, readerFactory)) {     return true;    }   }  }  return false; }}     &lt;/textarea&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-1398392321165022619?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/1398392321165022619/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=1398392321165022619&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/1398392321165022619'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/1398392321165022619'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2011/01/how-to-auto-scan-jpa-entities-using.html' title='How to auto scan jpa entities? (using spring configuration)'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-7611674555935287172</id><published>2008-02-11T14:37:00.000-08:00</published><updated>2008-02-11T14:45:49.179-08:00</updated><title type='text'>Hibernate property default for hbm2ddl</title><content type='html'>While using hbm2ddl for schema creation and update, if you want it to set a default value for the new column, use "default" property in hbm.&lt;br /&gt;&lt;br /&gt;Example:&lt;br /&gt;&amp;lt;property name="initialSize" type="int"&amp;gt;&lt;br /&gt;                &amp;lt;column name="INITIAL_SIZE" not-null="false" unique="false" sql-type="INTEGER"  &lt;strong&gt;default="3"&lt;/strong&gt;/&amp;gt;&lt;br /&gt;            &amp;lt;/property&amp;gt;&lt;br /&gt;&lt;br /&gt;Although hibernate documentation also mention to have insert="false" attribute, but it seems to be working even otherwise. The resultant effect would be same as using default in alter/create table SQL statements for schema creation/update.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-7611674555935287172?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/7611674555935287172/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=7611674555935287172&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/7611674555935287172'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/7611674555935287172'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2008/02/hibernate-property-default-for-hbm2ddl.html' title='Hibernate property default for hbm2ddl'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-8775096364236227867</id><published>2008-02-11T11:46:00.000-08:00</published><updated>2008-02-11T11:49:30.649-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Bypass lazy initialization in HQL.'/><category scheme='http://www.blogger.com/atom/ns#' term='HQL fetch'/><title type='text'>Bypassing lazy initialization in HQL</title><content type='html'>When you have lazy initialization turned on (default) in hibernate, you have to invoke seperate getter/find quary to retrieve child collections. &lt;br /&gt;Sometimes you want to bypass lazy initialization for instance during schema migration. &lt;br /&gt;&lt;br /&gt;You can use Hibernate HQL semantics of "fetch" to retrieve child collection in one query. &lt;br /&gt;&lt;br /&gt;Example: &lt;br /&gt;from MyEntity as me inner join fetch me.childEntityCollection &lt;br /&gt;&lt;br /&gt;The above query gets MyEntity with child childEntities already populated instead of proxy holders.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-8775096364236227867?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/8775096364236227867/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=8775096364236227867&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/8775096364236227867'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/8775096364236227867'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2008/02/bypassing-lazy-initialization-in-hql.html' title='Bypassing lazy initialization in HQL'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-8900346735691790456</id><published>2007-10-25T18:04:00.001-07:00</published><updated>2008-02-11T08:32:05.656-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='govind mekala'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate refresher'/><category scheme='http://www.blogger.com/atom/ns#' term='govind'/><category scheme='http://www.blogger.com/atom/ns#' term='Avoid loading all objects to find count in hibernate.'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate quick look'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate points'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate guide'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate tips'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate best practices'/><title type='text'>Performance tuning and unit testing hibernate application.</title><content type='html'>For complete list of hibernate best practices visit this blog home: &lt;a href="http://hibernatebp.blogspot.com/"&gt;http://hibernatebp.blogspot.com/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;There is a decent tutorial on testing hibernate mappings using Junit at &lt;a href="http://today.java.net/pub/a/today/2005/10/11/testing-hibernate-mapping.html?page=1"&gt;http://today.java.net/pub/a/today/2005/10/11/testing-hibernate-mapping.html?page=1&lt;/a&gt;&lt;br /&gt;Unitils is a java open source which uses standard unite testing framework such as JUnit, DBUnit and EasyMock. Unitils contains a very simple but powerful mapping test. This test checks whether the mapping of all Hibernate mapped objects is consistent with the database. To activate it, just add following test to your test suite:&lt;br /&gt;&lt;br /&gt;@SpringApplicationContext({"classpath:services-config.xml", "classpath:test-ds-config.xml"})&lt;br /&gt;public class HibernateMappingTest extends UnitilsJUnit3 {&lt;br /&gt;    public void testMappingToDatabase() {&lt;br /&gt;    HibernateUnitils.assertMappingWithDatabaseConsistent();    }}&lt;br /&gt;&lt;br /&gt;Suppose that the column PERSON.FIRSTNAME is missing in the test database. This will make the test fail with a message indicating that this column should be added:&lt;br /&gt;AssertionFailedError: Found mismatches between Java objects and database tables. Applying following DDL statements to the database should resolve the problem: alter table PERSON add column firstName varchar(255);&lt;br /&gt;&lt;br /&gt;For more details about unitils refer to &lt;a href="http://unitils.sourceforge.net/spring_article.html"&gt;http://unitils.sourceforge.net/spring_article.html&lt;/a&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;ORMUnit from the author of "POJOs in Action" also comes very handy for testing hibernate based applications.It could be now downloaded from &lt;a href="http://code.google.com/p/ormunit/"&gt;http://code.google.com/p/ormunit/&lt;/a&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;u&gt;Guidelines to choose between session management strategy:&lt;/u&gt;&lt;br /&gt;A basic Hibernate client/server application may be designed with server-side units of work that span a single client request.When a request from the application user requires data access, a new unit of work is started. The unit of work endswhen processing is complete and the response for the user is ready. This is session-per-request strategy.&lt;br /&gt;In a scenario like web applications, you don’t usually maintain a database transaction across a user interaction. Users take a long time to think about modifications. You can handle this scenario either by extending the persistence context or using detached objects. Hibernate objects are automayically detached when session is closed. You have to just call update to reattach it with session. This strategy is called session-per-request-with-detached objects.&lt;br /&gt;You can also extend a persistence context to span the whole transaction unit. That is session per application transaction which spans across multiple requests. Also known as sesseion per conversation.&lt;br /&gt;session-per-request-with-detached-objects is more of a BMP in context of EJBs. You have to pragrammatically take care of detached objects. Whereas session-per-conversation is loosely similar to CMP where hibernate will take care of it per unit of work.&lt;br /&gt;At the end of a unit of work, all the modifications you made, have to be synchronized with database through SQL DML statements. This process is called flushing of the persistence context. If a single property of an object is changed twice in the same persistence context, Hibernate needs to execute only one SQL UPDATE.Hibernate flushes occur at the following times:&lt;br /&gt;When a Transaction on the Hibernate API is committed Before a query is executed&lt;br /&gt;When the application calls session.flush() explicitly&lt;br /&gt;&lt;br /&gt;You can control this behavior by explicitly setting the Hibernate FlushMode via call to session.setFlushMode(). The default flush mode is FlushMode.AUTO and enables the behavior described previously. If you chose FlushMode.COMMIT, the persistence context isn’t flushed before query execution. It is flushed only when you call Transaction.commit() or Session.flush() manually. Repeated flushing of the persistence context is often a source for performance issues, because all dirty objects in the persistence context have to be detected atflush-time. A common cause is a particular unit-of-work pattern that repeats aquery and update sequence many times. Every update leads to a flush and a dirty check of all persistent objects, before each query. A Flush-Mode.COMMIT may be appropriate in this situation. The performance of the flush setting also depends on the size of the persistence context i.e the number of persistent objects it manages.&lt;br /&gt;Hibernate supports query cache which stores the primary keys of the objects found by a query. When it executes a query hibernate looks into query cache for the results before accessing the database. A query cache is useful for read only data because hibernate flushes all cached queries that involves a modified table.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;In order to  decide whether to leave the default lazy loading or go for eager loading, you should analyze relationships that are traversed in each request. If the application always traverses a relationship, it should be early loaded. By default hibernate lazily loads objects and collection and uses seperate SQL SELECT statement for each object or collection. In eager loading all the objects would be fetched in single SELECT.&lt;br /&gt;Sometime different requests require different objects to be eagerly loaded. A fetch join identifies relationship to eagerly load. HQL with fetch join ignores lazy loading settings specified in mapping.&lt;br /&gt;Example:&lt;br /&gt;&lt;br /&gt;from Order orderleft outer join fetch order.catalogleft outer join fetch order.lineitems as lineitemsleft outer join fetch lineitem.product where order.id = ?&lt;br /&gt;&lt;br /&gt;There are several limitations to fetch join such as duplicate data and ability to fetch only single collection. Also it is too verbose.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;In hibernate Session is your 1st level cache. Hibernate has a pluggable 2nd level caching architecture and there are several caching frameworks such as EHCache that supports process level cache. In hibernate caching is configured on per class or per collection basis. If you specify read-only, objects that are never modified by application are cached. If you specify read/write, objects that are modiefied by application are cached.&lt;br /&gt;&amp;lt;class name="Catalog" table="catalog"&amp;gt;&amp;lt;cache usage="read-write"/&amp;gt; -------------------&amp;lt;/cache&amp;gt;&lt;br /&gt;Objects configured for cache should be lazy loaded.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;If you use the identifier as part of your equals() and hashCode() implementation, add the entity to a Set before you save it.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;I personally do not like java annotations but if you want to use it for out of box validation, here is a decent tutorial:&lt;a href="http://www-128.ibm.com/developerworks/java/library/j-hibval.html"&gt;http://www-128.ibm.com/developerworks/java/library/j-hibval.html&lt;/a&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt; &lt;/p&gt;&lt;ul&gt;&lt;li&gt;Choose the right inheritence mapping strategy which suits your needs. Debate with domain architect and comeup with right OO design. Sometimes a good OO design might not be necessarily good for performance. You can refer to: &lt;a href="http://www-128.ibm.com/developerworks/java/library/j-hibernate/"&gt;http://www-128.ibm.com/developerworks/java/library/j-hibernate/&lt;/a&gt;&lt;br /&gt; &lt;/li&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-8900346735691790456?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/8900346735691790456/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=8900346735691790456&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/8900346735691790456'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/8900346735691790456'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2007/10/performance-tuning-and-unit-testing.html' title='Performance tuning and unit testing hibernate application.'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-8850531992759053650</id><published>2007-10-23T19:35:00.000-07:00</published><updated>2008-02-11T08:32:35.284-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='govind mekala'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate refresher'/><category scheme='http://www.blogger.com/atom/ns#' term='govind'/><category scheme='http://www.blogger.com/atom/ns#' term='Avoid loading all objects to find count in hibernate.'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate quick look'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate points'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate guide'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate tips'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate best practices'/><title type='text'>Some standard practices.</title><content type='html'>For complete list of hibernate best practices visit this blog home: &lt;a href="http://hibernatebp.blogspot.com/"&gt;http://hibernatebp.blogspot.com/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;You know it but just a reminder that HQL queries refer to object properties not database column's.&lt;/li&gt;&lt;li&gt;Realize mapping with respect to the database table model you are expecting. Whether you are using middlegen to start your hibernate project from existing schema or starting from scratch, you should visualize the outcome in terms of traditional db model and SQLs.It takes the surprise factor out and makes the design more predictable specially when you want to choose between association/composition or inheritance/composition.&lt;/li&gt;&lt;li&gt;Properties or attributes of POJO class need not be public. Hibernate's fundamental persistence architecture is based on reflection. Hibernate only enforces for having accessor getters and setters methods. This is more of a good OO design practice to keep class attributes private.&lt;/li&gt;&lt;li&gt;Place hbm.xml file in same package as your source. It will be useful while packaging as jar for web applications.&lt;/li&gt;&lt;li&gt;Creating session factory is a slow operation. You can take help from spring to maintain single session factory throughout your application per database. Session Factory is thread safe anyway. Please note that session object is not thread safe and it should be retrieved from session factory as and when required. Hibernate defines two states for any mapped object: transient and persistent. Transient object is like disassociated object and mapped is associated with a particular session.&lt;/li&gt;&lt;li&gt;Implement object versioning if required to resolve conflict. Most of the time you work with offline set of objects and persist them when required. It is advised to implement some sort of high level object versioning mechanism. Hibernate does not lock objects in memory. Your application can expect the behavior as defined by the isolation level of your database transactions. Hibernate provides automatic versioning and most of the cases it is sufficient. Many business processes require a whole series of interactions with the user interleaved with database accesses. Hibernate can automatically detect if a concurrent modification occured during user think time. It checks at the end of the conversation. Hibernate checks instance versions during flush, throwing an exception if conflicting updates occured. If you set optimistic-lock="dirty" when mapping &lt;class&gt;, Hibernate will only compare dirty fields during flush.&lt;/li&gt;&lt;li&gt;Use Named queries and paremeters: Named queries and paremeters makes program more readable. Named parameters are identified by ":". Query interface has type safe methods like setString, setTime to set values. &lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Example of mapping document with named query:&lt;/p&gt;&lt;p&gt;&amp;lt;hibernate-mapping"&amp;gt;.........................&lt;/p&gt;&lt;p&gt;&lt;hibernate-mapping&gt;&lt;/p&gt;&lt;p&gt;&amp;lt;query name="com.mydeveloperconnection.hibernateBP"&amp;gt;&lt;/p&gt;&lt;p&gt;&amp;lt;![CDATA[ from com.mydeveloperconnection.hibernateBP.Test as test where test.bpno "&amp;gt;= :bpnum ]]"&amp;gt;&amp;lt;/query"&amp;gt;.................&amp;lt;/hibernate-mapping"&amp;gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-8850531992759053650?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/8850531992759053650/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=8850531992759053650&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/8850531992759053650'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/8850531992759053650'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2007/10/hibernate-best-practices.html' title='Some standard practices.'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-3947863294628479356</id><published>2007-09-25T19:18:00.000-07:00</published><updated>2008-02-11T08:33:10.595-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Avoid loading all objects to find count in hibernate.'/><title type='text'></title><content type='html'>For complete list of hibernate best practices visit this blog home: &lt;a href="http://hibernatebp.blogspot.com/"&gt;http://hibernatebp.blogspot.com/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span &gt;&lt;strong&gt;&lt;span style="color:#006600;"&gt;&lt;u&gt;Avoid loading all objects to find count&lt;/u&gt;&lt;/span&gt;&lt;/strong&gt;: This is a classic case, where we want total count of entity in database. Avoid loading all objects and iterating through them to find count. Here is a simple way:&lt;/span&gt;&lt;/p&gt;&lt;span &gt;&lt;p&gt;&lt;br /&gt;return (Integer) getHibernateTemplate().execute( new HibernateCallback() &lt;/p&gt;&lt;p&gt;{ &lt;/p&gt;&lt;p&gt;public Object doInHibernate( Session session ) throws HibernateException,SQLException {&lt;/p&gt;&lt;p&gt;Query query = session.createQuery("select count(id) from My_Entity");&lt;/p&gt;&lt;p&gt;return ( (Long) query.iterate().next() ).intValue(); &lt;/p&gt;&lt;p&gt;} &lt;/p&gt;&lt;p&gt;} );&lt;/span&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-3947863294628479356?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/3947863294628479356/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=3947863294628479356&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/3947863294628479356'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/3947863294628479356'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2007/09/avoid-loading-all-objects-to-find-count.html' title=''/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-35989613.post-7623128970009734567</id><published>2007-06-21T07:59:00.000-07:00</published><updated>2008-02-11T08:33:50.744-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='govind mekala'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate refresher'/><category scheme='http://www.blogger.com/atom/ns#' term='govind'/><category scheme='http://www.blogger.com/atom/ns#' term='Avoid loading all objects to find count in hibernate.'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate quick look'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate points'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate guide'/><category scheme='http://www.blogger.com/atom/ns#' term='hibernate tips'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate best practices'/><title type='text'>Who should use hibernate?</title><content type='html'>For complete list of hibernate best practices visit this blog home: &lt;a href="http://hibernatebp.blogspot.com/"&gt;http://hibernatebp.blogspot.com/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;span style="color:#006600;"&gt;&lt;u&gt;Who should use hibernate?&lt;/u&gt;&lt;/span&gt;&lt;/strong&gt;&lt;br /&gt;Hibernate implements Java Persistence and supports all the standardized mappings,&lt;br /&gt;queries, and APIs. Before we start with hibernate best practices, lets see who needs hibernate.&lt;br /&gt;Hibernate is suitable for:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Application supporting various database and want to focus of their business logic instead of basic persistence mechanism.&lt;/li&gt;&lt;li&gt;Application which already have to data store and want to remove clutter of SQLs all over the code to better organized and maintained piece of software.&lt;/li&gt;&lt;li&gt;Applications which require seamless integration with caching APIs.&lt;/li&gt;&lt;li&gt;Applications driven by model such as UML. Declarative mappings in the form of XML is one of the reason for hibernate's popularity. There are several MDA tools such AndroMDA, middlegen which facilitates generating hibernate mapping file automatically and java code from it.&lt;/li&gt;&lt;li&gt;Many more..&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;However hibernate is not meant for die hard fans of complex SQLs and for application where large portion of business logic reside in their mile long stored procedures. Hibernate is also not yet designed for large scale data warehousing or data mart applications which uses underlying database server's additional capabilities for performance and scalability. A dashboard application working on top of data warehouse can use hibernate efficiently.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/35989613-7623128970009734567?l=hibernatebp.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://hibernatebp.blogspot.com/feeds/7623128970009734567/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=35989613&amp;postID=7623128970009734567&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/7623128970009734567'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/35989613/posts/default/7623128970009734567'/><link rel='alternate' type='text/html' href='http://hibernatebp.blogspot.com/2007/06/hibernate-implements-java-persistence.html' title='Who should use hibernate?'/><author><name>Govind Mekala</name><uri>http://www.blogger.com/profile/16146824452929405425</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='29' src='http://3.bp.blogspot.com/-Jcm9uOXqtrU/Tqi8f1NNBdI/AAAAAAAABIk/2NFFsfEcxrs/s220/Semiformal.jpg'/></author><thr:total>0</thr:total></entry></feed>
