2

我正在尝试使用休眠 4 和 Spring 3 实现一个简单的 DAO。

当我尝试在数据库中保存或删除一行时,事务不会持久化。我已经包含了一些代码来显示如何保存在 db 中不起作用:

我有一个 junit 测试,它只是尝试将 StockEntityDTO 保存在数据库中。

@RunWith(SpringJUnit4ClassRunner.class)
public class StocksDAOImplTest extends
    AbstractTransactionalJUnit4SpringContextTests {

@Autowired
protected StocksDAO stockDao;


@Test
public void shouldInsertIntoDatabase() {
    BigDecimal price = new BigDecimal(653.50);
    StockEntityDTO savedStock = new StockEntityDTO("GOOG", price, "google");
    stockDao.create(savedStock);
    StockEntityDTO retrievedStock = stockDao.getById(savedStock.getId());
    assertEquals(savedStock, retrievedStock);
}

测试通过,但预期的行(1,“GOOG”,653.50,“google”)未保存在数据库中。

DAO 看起来像这样:

@Transactional
public abstract class AbstractHibernateDAO<T extends Serializable> {

private Class<T> clazz;


@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;


public void setClazz(final Class<T> clazzToSet) {
    this.clazz = clazzToSet;
}


public void create(final T entity) {
    Session session = this.getCurrentSession();
    session.save(entity);

}

应用环境:

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

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
    <property name="username" value="gtp" />
    <property name="password" value="gtp" />
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.ubs.gtp.data.domain" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext
            </prop>
        </props>
    </property>
</bean>

希望有人可以提供帮助。从我的代码中可能很明显,我对 spring 很陌生。

4

1 回答 1

1

AbstractTransactionalJUnit4SpringContextTests rolls back after the test. Try setting a breakpoint at the last line and then inspecting the database. You can use the Rollback annotation if you don't want this default behaviour.

于 2012-10-06T10:14:59.507 回答