2

我已经测试了很长时间并搜索了几个小时。由于有一些类似的问题,但尝试后仍然无法正常工作,我正在使用spring MVC和jpa和hibernate来建立一个基础项目,但问题是当我将实体放入数据库时​​我无法将它保存到数据库中码头。奇怪的是,Junit 测试通过了。

这是基本代码。

web.xml

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>controller</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/controller.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>controller</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

db-context.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: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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <!-- DBCP DataSource -->
    <bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/spring" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <!-- JPA EntityManagerFactory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <bean id="jpaVendorAdapter"
                class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
            </bean>
        </property>
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Persistence Context Annotated -->
    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
        id="persistenceAnnotationBeanPostProcessor" />

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

    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

persistence.xml(在 META-INF 文件夹中)

<?xml version="1.0" encoding="UTF-8"?>
<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="persist" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.transaction.flush_before_completion"
                value="true" />
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
        </properties>
    </persistence-unit>

</persistence>

Person.java(实体 bean)

@Entity
public class Person {

    private int id;
    private String name;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    // ..

}

PersonDaoImpl.java

@Repository
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class PersonDaoImpl implements PersonDao {

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public Person persist(Person person) {
        entityManager.persist(person);
        return person;
    }

    // ...

}

PersonServiceImpl.java

@Service
public class PersonServiceImpl implements PersonService {

    private PersonDao personDao;

    @Inject
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    public Person create(Person person) {
        return personDao.persist(person);
    }

    // @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public Person save(Person person) {
        return personDao.merge(person);
    }

    // ...

}

人控制器.java

@Controller
@Scope("prototype")
@RequestMapping("/person")
public class PersonController {

    private PersonService personService;

    @Inject
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView add(@RequestParam("username") String name) {
        Person person = new Person();
        person.setName(name);
        System.out.println(name);  // i can get the value
        personService.create(person); // nothing happend... throws no Excp
        ModelAndView mav = new ModelAndView();
        mav.setViewName("result");
        mav.addObject("val", person.getName());
        return mav;
    }

}

PersonControllerTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/test-context.xml")
public class PersonControllerTest {

    private PersonController controller;

    @Inject
    public void setController(PersonController controller) {
        this.controller = controller;
    }


        // the test passed no matter @Transactional or not, if not, the db get the row
    @Test(/*expected = NullPointerException.class*/)
    @Transactional
    public void testAdd() {
//      PersonController controller = new PersonController();
        assertEquals("test", controller.add("test").getModelMap().get("val"));
    }

}

省略了一些 xml,如 context 和 mvc config xml 和 import 声明,servie 和 dao 接口,有人可以帮我吗?

4

1 回答 1

2

Spring Junit 不应该(并且默认情况下不会)持久化到数据库中。

如果您希望数据持久保存在数据库中,请将此行添加到您的测试类中。

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
于 2012-12-21T08:52:38.660 回答