Announcement Announcement Module
Collapse
No announcement yet.
Spring configuration for Hibernate testing Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring configuration for Hibernate testing

    Hi,

    I'm new to Spring. I read a lot of tutorials and googled for examples but still have troubles setting a working code.

    Here is my case: I'd like to save an entity Person to database eith Hibernate (annotations).
    I'd like to set the environment to actually be able to test the code, without running a web server. Anyway, somewhere I am missing something, becaue I get following exception:

    PHP Code:
    Caused byorg.springframework.beans.factory.BeanCreationExceptionCould not autowire method: public void org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests.setDataSource(javax.sql.DataSource); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionExceptionNo matching bean of type [javax.sql.DataSourcefound for dependencyexpected at least 1 bean which qualifies as autowire candidate for this dependencyDependency annotations: {}
        
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:608)
        
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
        
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283)
        ... 
    26 more
    Caused by
    org.springframework.beans.factory.NoSuchBeanDefinitionExceptionNo matching bean of type [javax.sql.DataSourcefound for dependencyexpected at least 1 bean which qualifies as autowire candidate for this dependencyDependency annotations: {}
        
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:901)
        
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:770)
        
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:685)
        
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:559)
        ... 
    28 more 
    Here is my code:

    app-config.xml
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
        <!-- Scans within the base package of the application for @Components to configure as beans -->
        <context:annotation-config/>
        <context:component-scan base-package="objectverse.core.web" />
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
            <property name="locations">  
                <list>  
                    <value>/WEB-INF/spring/configuration_mysql.properties</value>  
                </list>  
            </property>  
        </bean>  

        <import resource="db-config.xml" />  

        <bean id="systemUserDao" class="objectverse.core.repository.SystemUserDAOImpl">
            <property name="sessionFactory" ref="sessionFactory"/>
          </bean>

    </beans>
    db-config.xml
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>  
    <beans 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            ">
              
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
            <property name="driverClass">  
                <value>${jdbc.driver.className}</value>  
            </property>  
            <property name="jdbcUrl">  
                <value>${jdbc.url}</value>  
            </property>  
            <property name="user">  
                <value>${jdbc.username}</value>  
            </property>  
            <property name="password">  
                <value>${jdbc.password}</value>  
            </property>  
        </bean>  
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
            <property name="dataSource">  
                <ref bean="dataSource" />  
            </property>  
            <property name="annotatedPackages" value="objectverse.core.model.**.*" />
            <property name="hibernateProperties">  
                <props>  
                    <prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>  
                    <prop key="hibernate.hbm2ddl.auto">create</prop>  
                    <!-- uncomment this for first time run--> 
                    <prop key="hibernate.hbm2ddl.auto">create</prop>  
                    <prop key="hibernate.show_sql">false</prop>  
                </props>  
            </property>  
        </bean>  
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory">  
                <ref bean="sessionFactory" />  
            </property>  
        </bean>  
        <tx:annotation-driven transaction-manager="transactionManager"/>  
    </beans>
    My Test:

    PHP Code:
    package objectverse.core.repository;  


    import java.util.List;  
    import junit.framework.Assert;  

    import objectverse.core.model.SystemUser;

    import org.junit.Test;  
    import org.junit.runner.RunWith;  
    import org.springframework.beans.factory.annotation.Autowired;  
    import org.springframework.test.context.ContextConfiguration;  
    import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

    @
    RunWith(SpringJUnit4ClassRunner.class)  
    @
    ContextConfiguration(locations = { "/**/spring/app-config.xml" })
    public class 
    SystemUserDAOTest extends AbstractTransactionalJUnit4SpringContextTests {  
        
        @
    Autowired
        
    private SystemUserDAO dao;  
        
        @
    Test 
        
    public void testCreateData() {  
            
    int expectedResult 1;  
            
    SystemUser user = new SystemUser();  
            
    user.setName("Name");  
            
    user.setSurname("Surname");  
            
    dao.saveSystemUser(user);  
            
    Assert.assertEquals(expectedResultdao.getAllSystemUser(new SystemUser()).size());  
        }  
        
        ...

    SystemUser.java
    PHP Code:
    package objectverse.core.model;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;

    import org.hibernate.annotations.GenericGenerator;

    @
    Entity
    public class SystemUser {
            
        @
    Id 
        
    @GeneratedValue(generator "system-uuid")  
        @
    GenericGenerator(name "system-uuid"strategy "uuid")  
        @
    Column(name "uuid"
        private 
    String uuid;
        
        @
    Column(name "name"length 30 ,nullable false )
        private 
    String name;
        
    ...

    SystemUserDAO.java
    PHP Code:
    package objectverse.core.repository;

    import java.util.List;

    import objectverse.core.model.SystemUser;

    public interface 
    SystemUserDAO {
        public 
    void saveSystemUser(SystemUser user);  
        public List<
    SystemUsergetAllSystemUser(SystemUser user);  
        public 
    SystemUser selectSystemUserById(String userId);  
        public 
    void deleteSystemUser(SystemUser user);  

    SpringUserDAOImpl.java
    PHP Code:
    package objectverse.core.repository;

    import java.util.List;

    import objectverse.core.model.SystemUser;

    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;

    @
    Repository("systemUserDao")  
    @
    Transactional
    public class SystemUserDAOImpl implements SystemUserDAO {

        private 
    HibernateTemplate hibernateTemplate;
        
        public 
    SystemUserDAOImpl() {
            
    super();
        }
        
        @
    Autowired 
        
    public void setSessionFactory(SessionFactory sessionFactory) {  
            
    hibernateTemplate = new HibernateTemplate(sessionFactory);  
        }  

        @
    Transactional(readOnly false)  
        public 
    void saveSystemUser(SystemUser user) {  
            
    hibernateTemplate.saveOrUpdate(user);  
        }  

        @
    Transactional(readOnly false)  
        public 
    void deleteSystemUser(SystemUser user) {  
            
    hibernateTemplate.delete(user);  
        }  

        @
    SuppressWarnings("unchecked")  
        public List<
    SystemUsergetAllSystemUser(SystemUser user) {  
            return (List<
    SystemUser>) hibernateTemplate.find("from " 
                    
    SystemUser.class.getName());  
        }  

        public 
    SystemUser selectSystemUserById(String userId) {  
            return (
    SystemUser)hibernateTemplate.get(SystemUser.class, userId);  
        }  


    I really would need a hint why I get an exception. I checked a lot of examples and I don't see anything wrong.

    Greetings,
    Bojan

  • #2
    Check your full logging... Make sure the xml files can be found and loaded and not that some other test resource without a dataSource is located. The first lines of the logging show which xml files with which beans are being loaded.

    Comment


    • #3
      Where can I find full logging?

      Comment

      Working...
      X