简体   繁体   中英

Spring/JPA data persisting in unit test but not in application

I'm unable to persist data in my Spring/JPA/Tomcat application by calling my userService but when I call it from my unit test the data gets written to the database. Nor is there any exception thrown when calling the service from my controller.

Controller class:

@Controller
@RequestMapping("/")
public class AccessManagementController {

    @Autowired
    private UserService userService;

    @Autowired
    private ApplicationProperties applicationProperties;

    @RequestMapping(method = RequestMethod.GET, value = "/register")

        :
        :
        :

        userService.createNewUser(username, password);

        model.addAttribute("loginMessage", "Registration successful; you can now login");
        return "/access";
    }
}

Working unit test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:/spring/applicationContext.xml",
        "classpath:/spring/securityContext.xml",
        "classpath:/spring/jpaContext.xml"
})
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void userServiceSaveUserTest() {

        String testUsername = (new Date()).toString();

        userService.createNewUser(testUsername, "password");
        User findUser = userService.findByUsername(testUsername);
        Assert.assertNotNull(findUser);
        Assert.assertEquals(findUser.getUsername(), testUsername);
    }
}

applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.bytediary"/>

    <bean id="applicationProperties" class="com.bytediary.util.ApplicationProperties">
        <property name="location" value="classpath:application.properties"/>
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>

    <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/"/>

</beans>

jpaContext.xml:

<?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:jpa="http://www.springframework.org/schema/data/jpa"
       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.xsd
                           http://www.springframework.org/schema/data/jpa
                           http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <context:annotation-config />
    <context:component-scan base-package="com.bytediary.entity" />

    <jpa:repositories base-package="com.bytediary.repository"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="default"/>
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.bytediary.entity" />
        <property name="persistenceXmlLocation" value="classpath:/jpa/persistence.xml" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <property name="database" value="MYSQL" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />

</beans>

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
        <class>com.bytediary.entity.User</class>
    </persistence-unit>

</persistence>

1 . You do not need

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

Explanation here:

http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.html

Note: A default PersistenceAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom PersistenceAnnotationBeanPostProcessor bean definition.

2 . Try adding @Transactional to UserService.createNewUser().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM