11package com.manning.spock.warehouse.product
22
3+ import javax.persistence.EntityManager ;
4+ import javax.persistence.EntityManagerFactory ;
5+ import javax.persistence.Persistence
6+ 37import org.springframework.context.ApplicationContext
48import org.springframework.context.support.ClassPathXmlApplicationContext
9+ import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver
10+ import org.springframework.jdbc.datasource.DriverManagerDataSource
11+ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
12+ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
513import org.springframework.test.context.*
614
715import spock.lang.*
@@ -20,5 +28,38 @@ class ManualInjectionSpec extends spock.lang.Specification{
2028 allProducts. size() == 0
2129
2230 }
31+ 32+ def " Testing hibernate mapping of product class - mem db - no di at all" () {
33+ given : " a product DAO created programmatically without Spring"
34+ Map<String , String > properties = new HashMap<> ();
35+ properties. put(" javax.persistence.jdbc.driver" , " org.h2.Driver" );
36+ properties. put(" javax.persistence.jdbc.url" , " jdbc:h2:mem:myDatabaseForUnitTests" );
37+ properties. put(" hibernate.hbm2ddl.auto" , " update" );
38+ properties. put(" hibernate.show_sql" , " true" );
39+ properties. put(" hibernate.dialect" , " org.hibernate.dialect.H2Dialect" );
40+ EntityManagerFactory factory = Persistence . createEntityManagerFactory(" exampleFileBasedDatabase" ,properties);
41+ ProductLoader productLoader = new ProductLoader ();
42+ EntityManager em = factory. createEntityManager()
43+ productLoader. setEm(em);
44+ 45+ when : " we initially read products from the DB"
46+ List<Product > allProducts = productLoader. getAllProducts();
47+ 48+ then : " the db is empty"
49+ allProducts. size() == 0
50+ 51+ when : " we create one product"
52+ em. getTransaction(). begin();
53+ productLoader. createDefaultProduct();
54+ em. getTransaction(). commit();
55+ 56+ then : " the db should contain it if we read it again"
57+ productLoader. getAllProducts(). size() == 1
58+ 59+ cleanup : " in the end close database"
60+ em. close()
61+ factory. close()
62+ 63+ }
2364}
2465
0 commit comments