有人可以帮助有关Spring 3.1.0发布版本的Transaction

时间:2012-01-14 03:53:53

标签: java spring

   @Configuration
   @EnableTransactionManagement
   public class DataConfig {
        @Bean
        public DataSource dataSource() {
        BasicDataSource source = new BasicDataSource();
        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUrl("jdbc:mysql://localhost:3306/ligent?useUnicode=true&characterEncoding=gb2312");
        source.setUsername("root");
        source.setPassword("1qaz2wsx");
        source.setDefaultAutoCommit(false);
        return source;
        }
    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        HibernateTransactionManager bean = new HibernateTransactionManager();
        bean.setSessionFactory(sessionFactory().getObject());
        return bean;

    }
    private Properties hProps() {
    Properties p = new Properties();
    p.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    p.put("hibernate.cache.use_second_level_cache", "true");
    p.put("hibernate.cache.use_query_cache", "true");
    p.put("hibernate.cache.provider_class", "org.hibernate.cache.EhCacheProvider");
    p.put("hibernate.cache.provider_configuration_file_resource_path", "ehcache.xml");
    p.put("hibernate.show_sql", "true");
    p.put("hibernate.hbm2ddl.auto", "update");
    p.put("hibernate.generate_statistics", "true");
    p.put("hibernate.cache.use_structured_entries", "true");
    return p;
    }
@Bean
public IdTransferringMergeEventListener merge() {
    IdTransferringMergeEventListener bean = new IdTransferringMergeEventListener();
    return bean;
}
@Bean
public SimpleJdbcInsert simpleJdbcInsert() {
    return new SimpleJdbcInsert(dataSource());
}
@Bean
public JdbcTemplate jdbcTemplate() {
    JdbcTemplate aTemplate = new JdbcTemplate(dataSource());
    return aTemplate;
}
@Bean
public AnnotationSessionFactoryBean sessionFactory() {
    AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource());
    sessionFactoryBean.setNamingStrategy(new ImprovedNamingStrategy());
    sessionFactoryBean.setPackagesToScan(new String[]{ "ligent.model" });
    sessionFactoryBean.setHibernateProperties(hProps());
    Map<String, Object> eventListeners = new HashMap<String, Object>();
    eventListeners.put("merge", merge());
    sessionFactoryBean.setEventListeners(eventListeners);
    return sessionFactoryBean;
}
}

这是我的设置代码,我使用的是spring3.1.0。对于那个ralease包,我希望HibernateTransactionManager能够成功运行。当我运行更新时,删除事务, 这可以正常回滚。但测试插入失败。有人帮忙吗?

@Transactional
public void testInsert() {
    //jdbcTemplate.update("insert into book (title) values ('testInsert')");
    Book aBook =new Book();
    aBook.setTitle("test1");        
    getSession().save(aBook);
    throw new RuntimeException("runtime exception");        
}

但是在数据库上添加一行。为什么这段代码没有回滚???

1 个答案:

答案 0 :(得分:0)

看看@Transactional javadoc。您希望为回滚实际设置一些值。