Announcement Announcement Module
Collapse
No announcement yet.
spring + hibernate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • spring + hibernate

    hi
    we use tomcat, i need to move part of our project from java+ hibernate to spring + hibernate,
    step one
    we hibernate is work with jsp and java
    so we have like customer bean + customer.hbm.xml
    steptwo
    I know some simple spring control model + view
    step 3 I have spring controller .xml
    I want to insert some into database what else I should have?
    thank you

  • #2
    Try looking at the examples that ship with Spring they are very useful and should help explain your questions.

    Comment


    • #3
      hi I did , but I got
      Could not resolve placeholder 'com.mysql.jdbc.Driver'
      I still miss understand something
      Thank you

      Comment


      • #4
        hi all
        I have
        Code:
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
        <!--  - Application context definition for "springapp" DispatcherServlet.  -->
        
        <beans>
        
            <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                    <property name="location"><value>/WEB-INF/classes/hibernate.properties</value></property>
                </bean>
        
            <!-- Hibernate SessionFactory -->
            <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        
                <property name="driverClassName" >
                      <value>com.mysql.jdbc.Driver</value>
                  </property>
                  <property name="url" >
                    <value>jdbc:mysql://localhost:3306/test</value>
                </property>
                 <property name="username" >
                      <value>root</value>
                </property>
                <property name="password" >
                    <value>mysql</value>
                </property>
            </bean>
            <!-- Hibernate SessionFactory -->
                <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                    <property name="dataSource"><ref local="dataSource"/></property>
                    <property name="mappingResources">
                    <list>
                        <value>com/javacatz/hkgc/model/time_rules.hbm.xml</value>
                    </list>
                    </property>
                    <property name="hibernateProperties">
                        <props>
                            <prop key="hibernate.dialect">${org.hibernate.dialect.MySQLDialect}</prop>
                            <prop key="hibernate.connection.pool">1</prop>
                            <prop key="hibernate.show_sql">true</prop>
                        </props>
                    </property>
                </bean>
            
            <bean id="HibernateSpringDaoTarget" class="com.javacatz.hkgc.model.SpringHibernateDAOImpl">
                
        	<property name="sessionFactory" >
        		<ref local="sessionFactory"/>
        	</property>
        </bean>
        
            <!-- freemarker config -->
            <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
                <property name="templateLoaderPath" value="/jsp/freemarker/"/>
            </bean>
        
            <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
                <property name="cache" value="false"/>
                <property name="prefix" value=""/>
                <property name="suffix" value=".ftl"/>
        
                <!-- if you want to use the Spring FreeMarker macros, set this property to true -->
                <property name="exposeSpringMacroHelpers" value="true"/>
            </bean>
        
            <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                <property name="mappings">
                    <value>
                        mary.form=helpController
                        setrules.form=RestrictionController
                    </value>
                </property>
            </bean>
        
            <bean id="helpController"
                  class="com.javacatz.hkgc.controller.MaryController">
            </bean>
            <bean id="RestrictionController"
                  class="com.javacatz.hkgc.controller.RestrictionController">
            </bean>
        </beans>
        Code:
        package test
        public interface SpringHibernateDAO {
            public void saveRecord(time_rules setRuleToInsert);
        
        
        }
        package test
        import org.hibernate.cfg.Configuration;
        import org.hibernate.MappingException;
        import org.hibernate.HibernateException;
        import org.hibernate.SessionFactory;
        import org.hibernate.Session;


        public class SpringHibernateDAOImpl implements SpringHibernateDAO {

        private static SessionFactory sessionFactory = null;

        public SpringHibernateDAOImpl() {
        Configuration cfg = null;
        try {
        cfg = new Configuration().addClass(time_rules.class);
        } catch (MappingException e) {
        e.printStackTrace();
        }

        try {
        sessionFactory = cfg.buildSessionFactory();
        } catch (HibernateException e) {
        e.printStackTrace();
        }
        }//end of try

        private Session getSession() {
        Session session = null;
        try {
        session = sessionFactory.openSession();
        } catch (HibernateException e) {
        e.printStackTrace();
        }
        return session;
        }

        public void saveRecord(time_rules record) {
        Session session = this.getSession();
        try {
        session.saveOrUpdate(record);
        session.flush();
        } catch (HibernateException e) {
        e.printStackTrace();
        } finally {
        if (session != null) {
        try {
        session.close();
        } catch (HibernateException e) {
        e.printStackTrace();
        }
        }
        }
        }



        }

        Code:
        import junit.framework.TestCase;
        
        public class HibernateTest extends TestCase {
            private time_rules setRuleToInsert= null;
            private SpringHibernateDAO dao=null;
        
            protected void setUp() throws Exception{
            super.setUp();
                dao=new SpringHibernateDAOImpl();
            }
            protected void teatDown()throws Exception{
               super. tearDown();
            dao=null;
            }
           public void testsaveRecord() throws Exception{
                    setRuleToInsert = new time_rules();
                           setRuleToInsert.setHoursStar(8);
                           setRuleToInsert.setMinStar(20);
                           setRuleToInsert.setHoursEnd(9);
                            setRuleToInsert.setMinEnd(40);
                             setRuleToInsert.setHoursStar2(11);
                           setRuleToInsert.setMinStar2(10);
                           setRuleToInsert.setHoursEnd2(16);
                            setRuleToInsert.setMinEnd2(50);
                           dao.saveRecord(setRuleToInsert);
        }
        Code:
        import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
        
        public class HiberSpringinsert extends HibernateDaoSupport{
            public void saveRecord(time_rules setRuleToInsert){
                getHibernateTemplate().saveOrUpdate(setRuleToInsert);
            }
        }
        1) does my ideal about spring and Hibetnate have any mistake??
        2) my value come from from I wan to insert into database ,
        now I hard code in HibernateTest.java How can I test it?
        3) should I put my form requirement in Hibernatetest,java?
        thank you

        Comment


        • #5
          Why doesn't SpringHibernateDAOImpl just extend HibernateDaoSupport? It would get rid of all the Hibernate code for you.

          As for testing, might be a good idea to read the testing chapter of the reference manual.
          http://www.springframework.org/docs/...e/testing.html

          Comment


          • #6
            Hi right now I have
            view setrules and spring Control
            Code:
            package com.javacatz.hkgc.controller;
            
            import org.springframework.web.servlet.mvc.Controller;
            import org.springframework.web.servlet.ModelAndView;
            import org.apache.commons.lang.StringUtils;
            import org.hibernate.*;
            
            import javax.servlet.ServletException;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;
            import java.io.IOException;
            import java.util.HashMap;
            import java.util.Map;
            import java.util.Date;
            import com.javacatz.hkgc.service.ModuleFactory;
            import com.javacatz.hkgc.model.*;
            import com.javacatz.hkgc.util.StringFormater;
            import org.springframework.jdbc.datasource.DriverManagerDataSource;
            
            public class RestrictionController implements Controller {
                private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RestrictionController.class);
                 
            
                 SpringHibernateDAO dao=new SpringHibernateDAOImpl();
                /**
                 * basic control interface   */
            
            
            
                public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                        Map mapReturn = new HashMap();
                      mapReturn.put("endTime2", "");
                    String shour = (String) request.getParameter("shour");
            
                    String startHour = "";
                    if (shour != null) {
                        startHour = shour;
                    }
                    String smin = (String) request.getParameter("smin");
                    String startMin = "";
                    Date startTime = new Date();
                    if (smin != null) {
                        startMin= smin;
                         startTime = StringFormater.transformTime(startHour + ":" + startMin);
                    }
            
                     
                    String ehour = (String) request.getParameter("ehour");
                     String endHour = "";
                    if (ehour != null) {
                        endHour = ehour;
                    }
                     String emin = (String) request.getParameter("emin");
                      String endMin = "";
                       Date endTime = new Date();
                    if (emin != null) {
                        endMin = emin;
                          endTime = StringFormater.transformTime(endHour + ":" + endMin);
                    }
                    String shour2 = request.getParameter("shour2");
                     String startHour2 = "";
            
                       if (shour2 != null) {
                        startHour2 = shour2;
                    }
                    String smin2 = request.getParameter("smin2");
                    String startMin2="";
                    Date startTime2=new Date();       
            
                     if (smin2 != null) {
                        startMin2 = smin2;
                          startTime2 = StringFormater.transformTime(startHour2 + ":" + startMin2);
                    }
            
                     String ehour2 = (String) request.getParameter("ehour2");
                     String endHour2="";
                        if(ehour2 !=null)
                        {
                           endHour2=ehour2;
                        }
                     String emin2 = (String)request.getParameter("emin2");
                      String endMin2="";
                      Date endTime2= new Date();
                       if(emin2 !=null) {
                           endMin2=emin2;
                        endTime2 = StringFormater.transformTime(endHour2 + ":" + endMin2);   
                       }
            
                       int hoursStar = startTime.getHours();
                      int minStar = startTime.getMinutes();
                      int hoursEnd = endTime.getHours();
                      int minEnd= endTime.getMinutes();
                       int hoursStar2 = startTime2.getHours();
                      int minStar2 = startTime2.getMinutes();
                      int hoursEnd2 = endTime2.getHours();
                      int minEnd2= endTime2.getMinutes();
            
                    String click = StringUtils.defaultString(request.getParameter("action"));
                        String action="";
                         if(click!=null)
                         {
                            action=click; 
                         }
                       if (action.equals("submit")) {
                        time_rules   setRuleToInsert = new time_rules();
                               setRuleToInsert.setHoursStar(hoursStar);
                               setRuleToInsert.setMinStar(minStar);
                               setRuleToInsert.setHoursEnd(hoursEnd);
                                setRuleToInsert.setMinEnd(minEnd);
                                 setRuleToInsert.setHoursStar2(hoursStar2);
                               setRuleToInsert.setMinStar2(minStar2);
                               setRuleToInsert.setHoursEnd2(hoursEnd2);
                                setRuleToInsert.setMinEnd2(minEnd2);
                               dao.saveRecord(setRuleToInsert);
                         
                       }    // end of submit
                    
                      
                      
                     // put the return value in root
                         
                       /* mapReturn.put("Time", startTime2);
                         mapReturn.put("hour", new Integer(hoursStar));
                         mapReturn.put("min", new Integer(minStar));
                        mapReturn.put("hour2", new Integer(hoursEnd));
                         mapReturn.put("min2", new Integer(minEnd));
                         mapReturn.put("action", action);
                   // mapReturn.put("debugstuff", inputResult1 + ":" + inputResult2);
                     return new ModelAndView("setrules", mapReturn);   */
                     return new ModelAndView("setrules");
                }
            }
            and springHibernateDAOImpl, and SpringHibernateDAO, but when I call my view view, iget error on
            Error registering bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/springapp-servlet.xml]: Could not resolve placeholder 'org.hibernate.dialect.MySQLDialect'
            why??

            Comment


            • #7
              Thats because you have a value of ${org.hibernate.dialect.MySQLDialect}, for your hibernate.dialect. In your hibernate.properties file its looking for a property called org.hibernate.dialect.MySQLDialect. I would suggest that you either add an entry to the properties file of hibernate.dialect=org.hibernate.dialect.MySQLDiale ct, and change the invalid placeholder to ${hibernate.dialect} or just remove ${} from the value altogether.

              Comment


              • #8
                Tank you for point out my mistake,
                but now I still can use the hibernate session
                I got java.lang.NullPointerException
                com.javacatz.hkgc.model.SpringHibernateDAOImpl.get Session(SpringHibernateDAOImpl.java:35)
                which is session = sessionFactory.openSession();
                on my SpringHibernateDAOImpl
                Code:
                package com.javacatz.hkgc.model;
                import  com.javacatz.hkgc.model.time_rules;
                import java.util.List;
                
                //import org.springframework.orm.toplink.SessionFactory;
                import org.hibernate.cfg.Configuration;
                import org.hibernate.MappingException;
                import org.hibernate.HibernateException;
                import org.hibernate.SessionFactory;
                import org.hibernate.Session;
                
                
                public class SpringHibernateDAOImpl implements SpringHibernateDAO {
                
                   private static SessionFactory sessionFactory = null;
                
                    public SpringHibernateDAOImpl() {
                      Configuration cfg = null;
                      try {
                       cfg = new Configuration().addClass(time_rules.class);
                           } catch (MappingException e) {
                             e.printStackTrace();
                              }
                
                            try {
                               sessionFactory = cfg.buildSessionFactory();
                           } catch (HibernateException e) {
                               e.printStackTrace();
                          }
                      }//end of try
                
                    private Session getSession() {
                            Session session = null;
                           try {
                           session = sessionFactory.openSession();
                         } catch (HibernateException e) {
                              e.printStackTrace();
                          }
                          return session;
                       }
                
                    public void saveRecord(time_rules record) {
                       Session session = this.getSession();
                        try {
                       session.saveOrUpdate(record);
                        session.flush();
                       } catch (HibernateException e) {
                               e.printStackTrace();
                             } finally {
                              if (session != null) {
                                     try {
                                         session.close();
                                     } catch (HibernateException e) {
                                         e.printStackTrace();
                                     }
                                 }
                              }
                         }
                
                
                
                }
                in xml i have
                <bean id="HibernateSpringDaoTarget" class="com.javacatz.hkgc.model.SpringHibernateDAOI mpl">
                <property name="sessionFactory" >
                <ref local="sessionFactory"/>
                </property>
                it is this part right?
                thank you

                Comment


                • #9
                  As I explained previously, you are already configuring Hibernate through the XML. You are setting Hibernate properties so you don't need to do this in your Dao. HibernateDaoSupport is an easy way of using Hibernate from Spring I would rewrite your code to use this. The mapping looks fine.

                  Code:
                  public class SpringHibernateDAOImpl extends HibernateDaoSupport implements SpringHibernateDAO {
                   
                      public void saveRecord(time_rules record) {
                          getHibernateTemplate().saveOrUpdate(record);
                          getHibernateTemplate().flush();  // this might be unrequired
                      }
                  }
                  The code looks far better.
                  Last edited by karldmoore; Dec 2nd, 2006, 06:29 AM.

                  Comment


                  • #10
                    Hi
                    follow your suggestion and got error
                    org.springframework.beans.factory.CannotLoadBeanCl assException: Error loading class [com.javacatz.hkgc.model.SpringHibernateDAOImpl] for bean with name 'HibernateSpringDaoTarget' defined in ServletContext resource [/WEB-INF/springapp-servlet.xml]: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/springframework/orm/hibernate/support/HibernateDaoSupport
                    Thank you

                    Comment


                    • #11
                      Your obviously missing a jar off the classpath. There are two versions of HibernateDaoSupport with different package names. If you using Hibernate3 use the one with 3 in the name otherwise not. You need to ensure either spring-hibernate3.jar or spring-hibernate2.jar is on the classpath if you aren't using spring.jar.

                      Comment


                      • #12
                        hi, thank you
                        you are right , where to got it, I search download from google. I did got it , by the way . do I my xml looks right
                        Code:
                        <?xml version="1.0" encoding="UTF-8"?>
                        <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
                        <!--  - Application context definition for "springapp" DispatcherServlet.  -->
                        
                        <beans>
                        
                            <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                                    <property name="location"><value>/WEB-INF/classes/hibernate.properties</value></property>
                                </bean>
                        
                            <!-- Hibernate SessionFactory -->
                            <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                        
                                <property name="driverClassName" >
                                      <value>com.mysql.jdbc.Driver</value>
                                  </property>
                                  <property name="url" >
                                    <value>jdbc:mysql://localhost:3306/hkgc_dev</value>
                                </property>
                                 <property name="username" >
                                      <value>root</value>
                                </property>
                                <property name="password" >
                                    <value>mysql</value>
                                </property>
                            </bean>
                            <!-- Hibernate SessionFactory -->
                        
                                <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                                    <property name="dataSource"><ref local="dataSource"/></property>
                                    <property name="mappingResources">
                                    <list>
                                        <value>com/javacatz/hkgc/model/time_rules.hbm.xml</value>
                                    </list>
                                    </property>
                                    <property name="hibernateProperties">
                                   
                                        <props>
                                    <!-- SQL dialect -->
                        
                                        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
                                               -->
                                            <!-- JDBC connection pool (use the built-in) -->
                                        <prop key="hibernate.connection.pool_size" >1</prop>
                        
                                        <!-- Enable Hibernate's automatic session context management -->
                                        <prop key="hibernate.current_session_context_class" >thread</prop>
                        
                                        <!-- Disable the second-level cache  -->
                                        <prop key="hibernate.cache.provider_class" >org.hibernate.cache.NoCacheProvider</prop>
                        
                                        <!-- Echo all executed SQL to stdout -->
                                        <prop key="hibernate.show_sql" >true</prop>
                        
                                        <!-- Drop and re-create the database schema on startup -->
                        
                                        <prop key="hibernate.hbm2ddl.auto" >create-drop</prop>
                        
                                        <prop key="hibernate.c3p0.min_size" >1</prop>
                                        <prop key="hibernate.c3p0.max_size" >5</prop>
                                        <prop key="hibernate.c3p0.timeout" >300</prop>
                                        <prop key="hibernate.c3p0.max_statements" >50</prop>
                                        <prop key="hibernate.c3p0.idle_test_preriod" >3000</prop>
                                         </props>
                                        </property>
                                    </bean>
                                 
                        
                        
                        
                            <bean id="HibernateSpringDaoTarget" class="com.javacatz.hkgc.Controller.RestrictionController">
                                
                        	<property name="sessionFactory" >
                        		<ref local="sessionFactory"/>
                        	</property>
                        </bean>
                        
                            <!-- freemarker config -->
                            <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
                                <property name="templateLoaderPath" value="/jsp/freemarker/"/> 
                            </bean>
                        
                            <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
                                <property name="cache" value="false"/>
                                <property name="prefix" value=""/>
                                <property name="suffix" value=".ftl"/>
                        
                                <!-- if you want to use the Spring FreeMarker macros, set this property to true -->
                                <property name="exposeSpringMacroHelpers" value="true"/>
                            </bean>
                        
                            <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                                <property name="mappings">
                                    <value>
                                        mary.form=helpController
                                        setrules.form=RestrictionController
                                        test.form=Test
                                       
                                    </value>
                                </property>
                            </bean>
                        
                            <bean id="helpController"
                                  class="com.javacatz.hkgc.controller.MaryController">
                            </bean>
                        
                        
                             <bean id="Test"
                                  class="com.javacatz.hkgc.controller.Test">
                            </bean>
                            <bean id="RestrictionController"
                                  class="com.javacatz.hkgc.controller.RestrictionController">
                                <!--
                                <property name="sessionForm"><value>true</value></property>
                                        <property name="commandName"><value>time_rules</value></property>
                                        <property name="commandClass"><value>com/javacatz/hkgc/model/time_rules</value></property>
                        
                                 -->       
                                        
                        
                            </bean>
                        </beans>

                        Comment

                        Working...
                        X