单元测试 @Transactional 注解

简单的对比介绍下用 @Transactional 注解和 不使用的区别

 @Before
    public void setUp() throws Exception {
        Software software = new Software();
        software.setViewable(false);
        software.setSoftChName("ruanjian");
        Software soft = softwareRepository.save(software);
        LOG.info("保存成功,软件名为:" + soft.getSoftChName());

        for (int i = 0; i <5 ; i++) {
            Software so=new Software();
            so.setSoftChName("软件"+i);
            so.setViewable(true);
            Software ware=softwareRepository.save(so);
            LOG.info("软件名"+ware.getSoftChName());
        }
    }

不使用该注解 -控制台打印

这里写图片描述


使用@Transactional注解 -控制台打印
这里写图片描述


使用@Transactional注解,Test类中每个方法执行完之后都会默认清空虚拟数据库中的数据,因此便不再需要每次执行完都要清空数据。
另一种方法就是加一个@after 方法

   @After
    public void teraDown(){
        System.out.println("原数据:"+softwareRepository.findAll().size());
        softwareRepository.deleteAllInBatch();
        System.out.println("清空后的数据:"+softwareRepository.findAll().size());
    }

控制台打印输出

如果不使用@Transactional 注解,同时也没有@after 方法清空数据库,那么@before 中的数据将会重复创建,数据将会积累。分情况使用。
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
一,集成 Spring 与 Hibernate 1,配置SessionFactory 1,配置 ---------------------- applicationContext.xml ------------------------ <!-- 配置SessionFactory(整合Hibernate) --> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 数据库连接信息 --> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="user" value="${username}"></property> <property name="password" value="${password}"></property> <!-- 其他配置 --> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="5"></property> <property name="minPoolSize" value="3"></property> <property name="acquireIncrement" value="2"></property> <property name="maxStatements" value="8"></property> <property name="maxStatementsPerConnection" value="5"></property> <property name="maxIdleTime" value="20"></property> </bean> </property> <!-- 指定hibernate的配置文件的位置 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> ---------------------- jdbc.properties ------------------------ jdbcUrl = jdbc:mysql:///itcastoa driverClass = com.mysql.jdbc.Driver username = root password = 1234 2,测试代码 @Test// 测试 SessionFactory 的配置 public void testSessionFactory(){ SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory"); Assert.assertNotNull(sessionFactory.openSession()); } 2,配置声明式事务(使用基于注解的方式) 1,配置 <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置基于注解的事务支持--> <tx:annotation-driven transaction-manager="transactionManager"/> 2,测试代码 1,Service类 @Service public class InsertUserService { @Resource private SessionFactory sessionFactory; @Transactional public void addUsers() { sessionFactory.getCurrentSession().save(new User()); // int a = 1 / 0; // 这行会抛异常 sessionFactory.getCurrentSession().save(new User()); } } 2,单元测试 @Test // 测试声明式事务 public void testTransaction() { InsertUserService service = (InsertUserService) ac.getBean("insertUserService"); service.addUsers(); } 3,在web.xml中配置 spring 的 OpenSessionInView 过滤器(解决抛LazyInitializationException的问题) 1,配置 <!-- 配置 spring 的 OpenSessionInView 过滤器 --> <filter> <filter-name>OpenSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInView</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> 2,LazyInitializationException异常说明 1,对于集合属性,默认是lazy="true"的,在第一次使用时才加载。 2,但在加载时,如果Session已经关掉了就会抛LazyInitializationException异常 二,集成 Spring 与 Struts2.1.8.1 1,在web.xml配置监听器(Spring Reference 15.2 Common configuration) <!-- 集成Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext*.xml</param-value> </context-param> 2,在struts-config.xml中配置controller(Spring Reference 15.4.1.1. DelegatingRequestProcessor) <!-- 集成Spring --> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor" /> </controller> 3,测试 1,写Action类与Service类 @Controller("testAction") @Scope("prototype") public class TestAction extends ActionSupport { @Resource private TestService testService; @Override public String execute(){ testService.saveTwoUser(); return SUCCESS; } } @Service public class TestService { @Resource private SessionFactory sessionFactory; @Transactional public void saveTwoUser() { sessionFactory.getCurrentSession().save(new User()); // int a = 1 / 0; // 这行会抛异常 sessionFactory.getCurrentSession().save(new User()); } } 2,在struts.xml中配置Action <!-- 测试 --> <action name="test" class="testAction"> <result>/test.jsp</result> </action> 3,部署到Tomcat中并访问测试。 4,说明: 1,在写Action时要指定 @Controller 与 @Scope("prototype") 2,在struts.xml中配置action时,在class属性中写bean的名称

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值