【发布时间】:2021-03-16 21:48:46
【问题描述】:
我有一个使用 JPA、Hibernate 和 Guice 设置持久性的服务(如果有用,我没有使用 Spring)。这是我的代码的第一个工作版本:
public class BookDao {
@Inject
protected Provider<EntityManager> entityManagerProvider;
protected EntityManager getEntityManager() {
return entityManagerProvider.get();
}
@Transactional
public void persist(Book book) {
getEntityManager().persist(book);
}
}
public class MyAppModule extends AbstractModule {
@Override
protected void configure() {
initializePersistence();
}
private void initializePersistence() {
final JpaPersistModule jpaPersistModule = new JpaPersistModule("prod");
jpaPersistModule.properties(new Properties());
install(jpaPersistModule);
}
}
但是现在我需要配置多个持久化单元。我正在遵循mailing list 中的建议,根据他们的说法,我应该将我的模块逻辑移动到一个私有模块。我按照建议做了,并创建了相同代码的第二个版本,更改如下:
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD, PARAMETER, METHOD })
public @interface ProductionDataSource {} // defined this new annotation
public class BookDao {
@Inject
@ProductionDataSource // added the annotation here
protected Provider<EntityManager> entityManagerProvider;
protected EntityManager getEntityManager() {
return entityManagerProvider.get();
}
@Transactional
public void persist(Book book) throws Exception {
getEntityManager().persist(book);
}
}
public class MyAppModule extends PrivateModule { // module is now private
@Override
protected void configure() {
initializePersistence();
// expose the annotated entity manager
Provider<EntityManager> entityManagerProvider = binder().getProvider(EntityManager.class);
bind(EntityManager.class).annotatedWith(ProductionDataSource.class).toProvider(entityManagerProvider);
expose(EntityManager.class).annotatedWith(ProductionDataSource.class);
}
private void initializePersistence() {
JpaPersistModule jpaPersistModule = new JpaPersistModule("prod");
jpaPersistModule.properties(new Properties());
install(jpaPersistModule);
}
}
新注释的 EntityManager 被 Guice 正确注入并且是非空的,但有趣的是:我的一些单元测试开始失败,例如:
class BookDaoTest {
private Injector injector;
private BookDao testee;
@BeforeEach
public void setup() {
injector = Guice.createInjector(new MyAppModule());
injector.injectMembers(this);
testee = injector.getInstance(BookDao.class);
}
@Test
public void testPersistBook() throws Exception {
// given
Book newBook = new Book();
assertNull(newBook.getId());
// when
newBook = testee.persist(newBook);
// then
assertNotNull(newBook.getId()); // works in the first version, fails in the second
}
}
在我的代码的第一个版本中,上面的最后一行有效:实体被持久化并具有新的 id。但是,在我的代码的第二个版本中(使用PrivateModule 并从中公开带注释的EntityManager)persist() 操作不再起作用,实体没有ID。可能是什么问题呢?我没有在我的环境中进行任何其他配置更改,也没有在日志中看到错误消息。如果您需要更多详细信息,请告诉我。
【问题讨论】:
标签: java jpa dependency-injection orm guice