如何从LocalContainerEntityManagerFactoryBean创建EntityManager

时间:2014-03-31 11:17:06

标签: java spring jpa h2 entitymanager

我正在尝试为JPA DAO类编写JUnit测试。

该类的构造函数需要一个EntityManager,所以我试图使用 LocalContainerEntityManagerFactoryBean创建一个。

一旦我创建了LocalContainerEntityManagerFactoryBean,我就在其上调用getObject(),希望能够检索EntityManagerFactory以允许我创建EntityManager,但是getObject()返回Null。

我也尝试过getNativeEntityManagerFactory(),但它也会返回Null。

我做错了什么?

(我使用H2作为数据库,但这不应该有任何区别)

以下是代码:

Map<String, String> properties = new HashMap<>();
properties.put("javax.persistence.jdbc.driver", "org.h2.Driver");
properties.put("javax.persistence.jdbc.url", "jdbc:h2:mem:MyUnitTest");

Properties addProperties = new Properties();
addProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
addProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");

LocalContainerEntityManagerFactoryBean emfCB = new LocalContainerEntityManagerFactoryBean();
emfCB.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class);
emfCB.setPackagesToScan("com.something.mymodel");
emfCB.setPersistenceUnitName("myUnit");
emfCB.setJpaPropertyMap(properties);
//emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); -> This doesn't work
emfCB.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emfCB.setJpaVendorAdapter(vendorAdapter);
emfCB.setJpaProperties(addProperties);

EntityManagerFactory emf = emfCB.getObject(); // -> This is Null !

MyDao dao = new MyDao(emf);

1 个答案:

答案 0 :(得分:0)

你需要在调用emfCB.getObject()之前先调用LocalContainerEntityManagerFactoryBean#afterPropertiesSet,因为你的emfCB应该在所有必需的属性都设置好之后被初始化,而且在使用bean之前,这是{的一部分{3}} 在春天。

所以你的代码将是:

...
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emfCB.setJpaVendorAdapter(vendorAdapter);
emfCB.setJpaProperties(addProperties);

emfCB.afterPropertiesSet();
EntityManagerFactory emf = emfCB.getObject(); // -> This won't be Null

MyDao dao = new MyDao(emf);