Announcement Announcement Module
Collapse
No announcement yet.
can't get hibernate to work Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • can't get hibernate to work

    hey everyone, i am a newbie at spring and hibernate and i'm a little unclear about the full relationship. nonetheless, i have the following code that i just can't figure out what i need to do in order to retrieve a value from the DB. it compiles fine and will deploy, but there isn't a value brought back for the name variable. my DB table only has two columns: name, application.

    web.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>/WEB-INF/classes/log4j.properties</param-value>
        </context-param>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
        </listener>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>2</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>*.htm</url-pattern>
        </servlet-mapping>
        <session-config><session-timeout>
                30
            </session-timeout></session-config><welcome-file-list><welcome-file>
                index.jsp
            </welcome-file></welcome-file-list>
        <jsp-config>
            <taglib>
                <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
                <taglib-location>/WEB-INF/tld/c.tld</taglib-location>
            </taglib>
            <taglib>
                <taglib-uri>http://java.sun.com/jsp/jstl/fmt</taglib-uri>
                <taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
            </taglib>
            <taglib>
                <taglib-uri>http://www.springframework.org/tags</taglib-uri>
                <taglib-location>/WEB-INF/tld/spring.tld</taglib-location>
            </taglib>
            <taglib>
                <taglib-uri>http://www.springframework.org/tags/form</taglib-uri>
                <taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
            </taglib>
            </jsp-config>
        </web-app>
    -----------------------------
    applicationContext.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
        
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="/WEB-INF/jdbc.properties"/>
        </bean>
        
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
        
        <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
        
        <!-- Hibernate SessionFactory -->
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="dataSource" ref="dataSource"/>
    		<property name="mappingResources">
    			<value>nicks.hbm.xml</value>
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    				<prop key="hibernate.show_sql">true</prop>
    				<prop key="hibernate.generate_statistics">true</prop>
                                    <prop key="hibernate.use_sql_comments">true</prop>
    			</props>
    		</property>
    		<property name="eventListeners">
    			<map>
    				<entry key="merge">
    					<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
    				</entry>
    			</map>
    		</property>
    	</bean>
            
            	<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory"/>
    	</bean>
    
    	<!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->
    	<!--
    	<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
    	-->
            
            	<!--
    	  - PetClinic's central data access object: Hibernate implementation.
        -->
    	<bean id="clinicTarget" class="org.samples.HibernateClinic">
    		<property name="sessionFactory" ref="sessionFactory"/>
    	</bean>
            
            	<!--
    		- Transactional proxy for PetClinic's central data access object.
    		-
    		- Defines specific transaction attributes with "readOnly" markers,
    		- which is an optimization that is particularly valuable with Hibernate
    		- (to suppress unnecessary flush attempts for read-only operations).
    		-
    		- Note that in a real-life app with multiple transaction proxies,
    		- you will probably want to use parent and child bean definitions
    		- as described in the manual, to reduce duplication.
        -->
    	<bean id="clinic" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    		<property name="transactionManager" ref="transactionManager"/>
    		<property name="target" ref="clinicTarget"/>
    		<property name="transactionAttributes">
    			<props>
    				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
    				<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
    				<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
    				<prop key="store*">PROPAGATION_REQUIRED</prop>
    			</props>
    		</property>
    	</bean>
    
    	<!-- Hibernate 3.0's JMX statistics service -->
    	<!-- Implements the StatisticsServiceMBean management interface -->
    	<bean name="petclinic:type=HibernateStatistics" class="org.hibernate.jmx.StatisticsService">
    		<property name="sessionFactory" ref="sessionFactory"/>
    	</bean>
        
    </beans>
    -------------------------------------------------------
    nicks.hbm.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    		"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <!--
      - Mapping file for the Hibernate implementation of the Clinic interface.
    	-->
    <hibernate-mapping auto-import="true" default-lazy="false">
    
    	<class name="org.samples.Test" table="example">
    		<id name="name" column="name">
    			<generator class="identity"/>
    		</id>
    		<property name="application" column="application"/>
    	</class>
    
    </hibernate-mapping>
    -------------------------------------------------------------
    Test.java
    Code:
    package org.samples;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    
    import org.springframework.beans.support.MutableSortDefinition;
    import org.springframework.beans.support.PropertyComparator;
    
    /**
     *
     * @author nleli
     */
    public class Test {
        
        private String name;
        
        private String application;
        
        /** Creates a new instance of Test */
        public Test() {
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getApplication() {
            return application;
        }
    
        public void setApplication(String application) {
            this.application = application;
        }
        
    }
    ----------------------------------------------------
    HibernateClinic.java
    Code:
    package org.samples;
    import java.util.Collection;
    
    import org.springframework.dao.DataAccessException;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import org.samples.Clinic;
    
    public class HibernateClinic extends HibernateDaoSupport implements Clinic {
        public Collection findTests(String lastName) throws DataAccessException {
            return getHibernateTemplate().find("from example");
        }
        
        public Test loadOwner(String name) throws DataAccessException {
            return (Test) getHibernateTemplate().load(Test.class, new String(name));
        }
        
        public void storeOwner(Test owner) throws DataAccessException {
                getHibernateTemplate().merge(owner);
        }
        
    }
    -------------------------------------------------------
    Clinic.java
    Code:
    package org.samples;
    
    import java.util.Collection;
    
    import org.springframework.dao.DataAccessException;
    
    
    public interface Clinic {
    
    	Collection findTests(String lastName) throws DataAccessException;
    
    	Test loadOwner(String name) throws DataAccessException;
    index.jsp
    Code:
    <%@ include file="/WEB-INF/jsp/includes.jsp" %>
    
    <html>
        <head>
            <title>index page</title>
        </head>
        <body>
            <h5>this is the /WEB-INF/jsp/index.jsp</h5>
            <table><TR><TD>Name</TD><TD><b><c:out value="${Test.getName}"/></b></TD></TR></table>
        </body>
    </html>
    Can anyone offer any guidance where i'm missing something? Thanks in advance!
    Last edited by nickleli; Jan 19th, 2007, 04:56 PM. Reason: clean up code

  • #2
    It really helps to wrap your code in [ code] [ /code] tags, otherwise its not readable. Can you edit it so I can read it? As for the problem can you give a little more information. I would also take a look at the petclinic example as a basis.

    Comment


    • #3
      sorry about that, i wasn't even aware. i wrapped the code and it's much more readable now ;-). i actually based this simple test on the petclinic application and i can't figure it out. essentially, there's not even much spring involved in this. i'm just loading the index page from a new project, and instead of a value from the database being displayed, nothing is entered in that field (i.e. in index.jsp where i state: <c:out value="${Test.getName}"). no compile errors occur or runtime errors. i can zip up my file directory if you think that would help?

      Comment


      • #4
        I can't really see how this will do anything. How are you querying the data from the server? There don't seem to be any servlets or controllers, basically anything to call the server. Why don't you try writing a simple test case to talk to the 'clinic' bean and take it from here. I'd try and get your head around Hibernate first and then try and integrate it with the web tier.

        Comment


        • #5
          that's exactly my problem. i can run through the hibernate tutorial/documentation and i understand what they're doing but it seems that every hibernate app i see has something completely different. when i analyze the petclinic app, i don't see how it works but i know it does as i can query the database and see all the owners i've entered from the web form. how does the petclinic handle the control? "how am i querying the data from the server?" i guess how the petclinic is, from within the HibernateClinic class. that is the only place i have found any sort of SQL statement looking in the database...

          Comment


          • #6
            Well you get from the JSP page to the server using SpringMVC. The beans for this (e.g. ClinicController) are defined within petclinic-servlet.xml. These controllers delegate to Clinic to do the actual loading. If you're using Hibernate the clinic bean is defined within applicationContext-hibernate.xml. In this, 'clinic' defines a proxy that provides transaction support, its target is the real clinic bean that load the Hibernate load (HibernateClinic.java).

            I would have a read of the reference manual in conjunction with the example to really understand it. Does that give you any more help?

            Comment


            • #7
              unfortunately, i've read through the "tutorial" section at the home page of the petclinic app until i was cross-eyed. i understand the MVC conceptually, but i can not map let's say the find owner event through it's lifecycle. i always seem to reach a dead end where i have no idea how the page is being rendered or where a call is going to...

              Comment


              • #8
                for instance, in the petclinic-servlet.xml document, what does this section mean:
                Code:
                	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                		<property name="mappings">
                			<props>
                				<prop key="/welcome.htm">clinicController</prop>
                				<prop key="/vets.htm">clinicController</prop>
                				<prop key="/findOwners.htm">findOwnersForm</prop>
                				<prop key="/owner.htm">clinicController</prop>
                				<prop key="/addOwner.htm">addOwnerForm</prop>
                				<prop key="/editOwner.htm">editOwnerForm</prop>
                				<prop key="/addPet.htm">addPetForm</prop>
                				<prop key="/editPet.htm">editPetForm</prop>
                				<prop key="/addVisit.htm">addVisitForm</prop>
                			</props>
                		</property>
                	</bean>
                in the spring documentation, i don't see any reference to the <prop> element, only property. is findOwnersForm mentioned above the same as org.springframework.samples.petclinic.web.FindOwne rsForm.java? i always thought class names were case sensitive? if it's not pointing to that java class, what is it referring to?

                Comment


                • #9
                  If might be worth having a look through some of the examples and tutorials on the net. There was also a discussion about the Spring books available.
                  http://forum.springframework.org/showthread.php?t=31398

                  I'm basically learning everything from the reference manual and the examples. You should be able to understand most of it, if you look through chapters 3, 9, 10, 11, 12 and 13. Once you've got your head round that the rest of it is also a good idea! As for your specific questions, see below......

                  This section discusses properties.
                  http://www.springframework.org/docs/...ction-elements

                  This section discusses mappings.
                  http://www.springframework.org/docs/...handlermapping

                  Comment


                  • #10
                    well, i was hoping there would be a quicker way to figure this out ...thanks for the info. i'll try reading more of the documentation.

                    Comment


                    • #11
                      I don't really know what to say. I'm sure if you look through the chapters I mentioned in conjunction with petclinic, you'll have it cracked in no time! I'd try just tweaking something simple in petclinic to see what happens and try to understand it. Add a new property to one of the objects and try to display it. Then add a new page to do something, etc.......

                      There are lots of other examples and tutorials on the web, might be worth trying some out.

                      Comment

                      Working...
                      X