Hibernate Persistence Unit Test using the Spring TestContext Framework

The Test:

@ContextConfiguration(locations = {"classpath:dataSource.xml",
	"classpath:applicationContext.xml"})
public class OrderPersistenceTest extends AbstractTransactionalJUnit4SpringContextTests {

        @Autowired
	private SessionFactory sessionFactory;

	@Autowired
	private HibernateTransactionManager transactionManager;

	@Autowired
	private OrderDao orderDao;

	@Test
	public void testCascadeOrderToOrderItem() {
		Order order = new Order("ORDER_NUMBER_1");
                OrderItem orderItem = new OrderItem("ITEM_ONE");

                orderDao.save(order);

                sessionFactory.getCurrentSession().flush(); 

                Assert.assertEquals(1, simpleJdbcTemplate.queryForInt("select count(*) from orderItem;"));
 	}

}

Some highlights:

  • By extending the class AbstractTransactionalJUnit4SpringContextTestsyou save some trouble with some annotations. This class gives you the following:
    • @RunWith(SpringJUnit4ClassRunner.class) which says run this class using JUnit4
    • @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) allows you to use things like @Autowired to inject your sessionFactory into your test instead of the bean context.
    • @TestExecutionListeners(TransactionalTestExecutionListener.class) && @Transactionalwhich makes each method in your test transactional
      • NOTE: by default it will Rollback the transaction at the end of your test method (to override you can use the annotation @Rollback(false)
  • @ContextConfiguration(locations = {“classpath:dataSource.xml”,”classpath:applicationContext.xml”})wires up your Spring configuration files (see below)
  • @Autowired is a quick way of injecting your beans from spring.

For more details see:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testcontext-framework

Background:

Hibernate configuration:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!--  Identity Domain Objects -->
		<mapping class="ca.intelliware.test.model.Order" />
		<mapping class="ca.intelliware.test.model.OrderItem" />
	</session-factory>
</hibernate-configuration>
@Entity
@Table

public class Order {
	@Id
	@Column
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;

        @OneToMany(mappedBy="order", fetch=FetchType.LAZY)
	@Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})
	private Set<OrderItem> orderItems = new TreeSet<OrderItem>();
}
@Entity
@Table

public class OrderItem {
	@Id
	@Column
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;

	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="order_id")
	private Order order;

        addNewOrderItem(OrderItem item) {
            item.setOrder(this);
            this.orderItems.add(item);
        }
}

Spring configuration:

applicationContext.xml

<!-- =================================================================== -->
    <!-- Session Factory Configuration                                       -->
    <!-- =================================================================== -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
		<property name="namingStrategy"><bean class="org.hibernate.cfg.ImprovedNamingStrategy"/></property>
	</bean>

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

    <!-- =================================================================== -->
    <!-- Dao's and Repositories                                        -->
    <!-- =================================================================== -->
	<bean id="orderDao" class="ca.intelliware.test.persistence.OrderDaoImpl">
  		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>

datasource.xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!--		 HSQL Data Source -->
		<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
		<property name="url" value="jdbc:hsqldb:file:target/hsqldb/testdb"/>
		<property name="username" value="sa"/>
		<property name="password" value=""/>
		<property name="maxActive" value="20"/>
		<property name="maxIdle" value="8"/>
		<property name="maxWait" value="-1"/>
    </bean>

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply