Announcement Announcement Module
Collapse
No announcement yet.
what is the difference between hibernate template and hibernate dao support. Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • what is the difference between hibernate template and hibernate dao support.

    HI All,

    hibernate dao support provides a in built method getHibernateTemplate.This is only the advantage of using hibernate dao support other than hibernate template.Please suggest.

    When we need to go for a hibernate template and hibernate dao support.

    Regards,
    sameer.

  • #2
    HibernateDaoSupport gives you easy access to a HibernateTemplate. But the usage of both isn't recommended anymore since about 2007 so simply use a plain SessionFactory...

    Comment


    • #3
      I am agree with Marten

      More information about this here
      So should you still use Spring's HibernateTemplate and/or JpaTemplate??

      Comment


      • #4
        Originally posted by dr_pompeii View Post
        I am agree with Marten

        More information about this here
        So should you still use Spring's HibernateTemplate and/or JpaTemplate??
        That post is from 2007 , is it still relevant ? Things may have change since then ?!
        I find HibernateTemplate very convenient , I just define and reconfige 3 beans and get this HibernateTemplate ready for use , with less work.


        Code:
        	private HibernateTemplate hibernateTemplate;
        
        	@Autowired
        	public void setSessionFactory(SessionFactory sessionFactory) {
        		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
        	}
        
        	@Override
        	@Transactional(readOnly = false)
        	public void saveUser(User user) {
        		hibernateTemplate.saveOrUpdate(user);
        	}
        
        	@Override
        	@Transactional(readOnly = true)
        	public User getUser(String email) {
        		return  (User) hibernateTemplate.find("from User where email =" + "'" + email + "'").get(0);
        	}
        why isn't it recommended ?

        Comment


        • #5
          Hello

          That post is from 2007 , is it still relevant ? Things may have change since then ?!
          Yes, relevant until now, why?. Due the follow

          The point is with HibernateTemplate makes Spring and Hibernate more coupled about dependencies about Java code (API level).

          I used to work years ago with this template and really does and done very well its job, but ...

          why isn't it recommended ?
          Therefore the actual solution (since 2007) practically let you work in a 100% with pure Hibernate API breaking this level about coupling between these frameworks, some differences about synthax between pure Hibernate and Spring's HibernateTemplate exits

          With the actual solution is only necessary add the Spring's annotation called @Repository to your DAO class and some xml configuration like, scanning packages and to recognize this annotation and add an Exception Translator to let Spring Translate the own Hibernate's type Exceptions to the Spring DataAccessException

          HTH

          Comment


          • #6
            Hi ,

            I still feel something is missing , from easy work , I need to write a lot more .

            Where I can learn how to implements right pure Hibernate API , Resource management , Transaction management & and Error handling ?
            I'm planning build a site with at least x000 ( and high growing potential) users online which will using this Hibernate API , using MySql . How to handle massive connections / SessionFactory usages?

            When implements pure Hibernate API using Spring , where Spring comes into the picture , I mean what's Spring's job here? Connection closed? Threads?

            (Sorry if it's basic Hibernate knowledge )

            Thanks and Regards ,

            Zakos

            Comment


            • #7
              You don't need to write more (not sure where you get that idea). How to implement plain hibernate api based dao's is explained in the spring reference guide.

              The HibernateTemplate isn't needed anymore since hibernate 3.0.1, since that release it became easier to plugin nicely to hibernate, before that spring needed some trickery, proxing and hackery to manage transactions, thread bound sessions and exception translation. Now with the newer versions of hibernate that isn't needed anymore, you still get all the nice stuff exception translation, session management etc. but without using any spring specific classes. Which imho is really nice it makes the use of spring even less obtrusive.

              The code you posted would be more like

              Code:
              	private SessionFactory sessionFactory;
              
              	@Autowired
              	public void setSessionFactory(final SessionFactory sessionFactory) {
              		this.sessionFactory = sessionFactory;
              	}
              
              	@Override
              	@Transactional(readOnly = false)
              	public void saveUser(final User user) {
              		sessionFactory.getCurrentSession().saveOrUpdate(user);
              	}
              
              	@Override
              	@Transactional(readOnly = true)
              	public User getUser(final String email) {
              		final String query = "from User where email=:email";
              		Query query = sessionFactory.getCurrentSession().createQuery(query);
              		query.setParameter("email", email);
              		List<User> results = query.list();
              		if (!results.isEmpty()) {
              			return results.get(0);
              		}
              		return null;
              	}
              If fixed your getUser method because that was flawed. NEVER NEVER NEVER (did I make myself clear) use string contact to include parameters into your query ALWAYS use placeholders, unless you want to be vulnerable to sql injection attacks! ALso you didn't check for any result which could potentially lead to exceptions.
              Last edited by Marten Deinum; Jul 11th, 2011, 01:41 AM. Reason: Fixed getUser method

              Comment


              • #8
                1. Clear Sir.

                2. Does the spring reference guide is this ? 13.3 Hiberante ? Didn't find Hibernate annotation example there.

                I use

                Code:
                	     <bean id="transactionManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                	    <property name="sessionFactory"> 
                	    	<ref bean="mySessionFactory" /> 
                	     </property>
                     </bean>
                	
                	<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                		<property name="dataSource" ref="myDataSource" />
                 		<property name="packagesToScan" value="com.domain" />
                		<property name="hibernateProperties">
                			<props>
                				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                				<prop key="hibernate.show_sql">false</prop>
                				<prop key="hibernate.hbm2ddl.auto"></prop>
                			</props>
                		</property>
                	</bean>
                3. Is the responsibility table here , is still apply on pure Hibernate API ?


                Thanks , again.

                Comment


                • #9
                  You should use 2 to configure your sessionfactory that doesn't change you only don't use HibernateTemplate anymore... The JDBC chapter has nothing to do with hibernate so don't see your question...But spring still manages your resources (connection, session, transaction) that doesn't change... As I tried to explain in the previous posts the only thing that changes is that you don't use HibernateTemplate anymore everything else remains the same!

                  Comment


                  • #10
                    But spring still manages your resources (connection, session, transaction) that doesn't change...
                    That's what I wanted to ask through the JDBC table example, well got it . I'll try to do the changes you suggests. ( that's where the idea for "more code" that I meant earlier , if it wasn't like that )

                    Comment


                    • #11
                      Hi again , ( Should I open a new thread? )

                      Thre are many configuration examples which make me confuse , I don't know what I need and what's right for me.
                      13.3 Hibernate chapter from the doc. has many options.
                      This change from template to nontemplate is frustrating , I even figure out I didn't have
                      Code:
                       <tx:annotation-driven/> 
                      ERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
                      org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
                      so the @Transactional was useless , and when using it I get an exception.

                      Is there a good Spring3+plain Hibernate API with MySql & annotation example?

                      When I did the minor change as you suggested , I get

                      Code:
                      javax.servlet.ServletException: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
                      Code:
                      package com.x.dao;
                      import java.util.List;
                      import com.x.domain.User;
                      public interface IUserDAO {
                      	public User getUser(String email);	
                      }
                      Code:
                      package com.x.dao;
                      import com.x.domain.User;
                      import java.util.List;
                      import org.hibernate.Query;
                      import org.hibernate.SessionFactory;
                      import org.springframework.beans.factory.annotation.Autowired;
                      import org.springframework.stereotype.Repository;
                      import org.springframework.transaction.annotation.Transactional;
                      @Repository("IuserDao")
                      @Transactional
                      public class UserDAOImpl implements IUserDAO {
                      
                      	 private SessionFactory sessionFactory;
                      
                      	@Autowired
                      	 public void setSessionFactory(final SessionFactory sessionFactory) {
                              this.sessionFactory = sessionFactory;
                          }
                      	@SuppressWarnings("unchecked")
                      	@Override
                      	@Transactional(readOnly = true)
                      	public User getUser(final String email) {
                      		final String _query = "from User where email=:email";
                      		Query query = sessionFactory.getCurrentSession().createQuery(_query);
                      		query.setParameter("email", email);
                      		List<User> results = query.list();
                      		if (!results.isEmpty()) {
                      			return results.get(0);
                      		}
                      		return null;	
                      	}
                      }

                      Code:
                      		<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
                      		    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
                      		    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/a"	/>
                      		    <property name="user" value="root"/>
                      		    <property name="password" value=""/>
                         		</bean>
                      	
                      	     <bean id="transactionManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                      	        <property name="sessionFactory" ref="mySessionFactory" />
                          	 </bean>
                      	
                      	<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                      		<property name="dataSource" ref="myDataSource" />
                       		<property name="packagesToScan" value="com.x.domain" />
                      		<property name="hibernateProperties">
                      			<props>
                      				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                      				<prop key="hibernate.show_sql">false</prop>			
                      				<prop key="hibernate.hbm2ddl.auto"></prop>
                      			</props>
                      		</property>
                      	</bean>
                      Thanks in advance!
                      Last edited by Zakos; Jul 13th, 2011, 06:37 AM.

                      Comment


                      • #12
                        You have @Transactional but not tx:annotation-driven, to make the getCurrentSession work you need to have proper transaction managment if not it will not work.

                        Comment


                        • #13
                          when using
                          <tx:annotation-driven />
                          I get

                          SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListe ner
                          org.springframework.beans.factory.BeanDefinitionSt oreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

                          UPDATE 1 :

                          added aopalliance-1.0.jar and Exception gone. and works!


                          UPDATE 2:

                          Marten Deinum ,

                          is this minor change , make my connection from Template to nontemplate ? to 'pure Hibernate API' ? Isn't there still coupling betwerem Spring and Hibernate , cuz Spring is the transaction manager?

                          Thx for ur support
                          Last edited by Zakos; Jul 13th, 2011, 08:07 AM.

                          Comment


                          • #14
                            THere is a coupling but it is a configuration detail only it isn't in your code anymore (we could argue about that when you use @Transactional although you could replace that with the JEE @TransactionAttribute reducing the spring coupling even more, but I'm more of an xml guy )... That way you would have a dao without any spring dependency but still useable by spring.

                            I suggest using maven/ant+ivy/gradle to manage your dependencies that saves you a ton of headaches searching for the correct jars.

                            Comment


                            • #15
                              On one hand when choosing to use Spring , you consider using Spring Tools which one of them is "DB Tools" which is great because you already added Spring to your system proejct so why not use what you already have , on the other hand you say its mkaing coupling , which I can say on every one of the Spring tool I got.
                              I understand that in programming world , the better the decoupling , the the better your code is ( better maintain / changes-ready / understand ) .

                              Starting learning how to use maven/ant+ivy/gradle will give me ton of headaches ?! although I see 'maven' word on many examples.

                              Comment

                              Working...
                              X