春には、classpathxmlapplicationcontextを使用してentitymanagerを取得するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/1891320

  •  19-09-2019
  •  | 
  •  

質問

春を使用すると、次のプロパティで豆を自動化できます。

@PersistenceContext(unitName="foo") private EntityManager em;

以下を使用して、「SomeBean」を豆に手動で自動させることができます。

ClassPathXmlApplicationContext ctx = 
      new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
AutowireCapableBeanFactory fac = ctx.getAutowireCapableBeanFactory();
fac.autowireBean(someBean);

ただし、特定のEntityManagerを直接取得する方法を理解することはできません。ユースケースは、すべてのEntityManagerオブジェクトを取得し、それらに簡単なクエリを実行して、それらが適切にセットアップされることを確認するテストを作成したいということです。これを行うには、アプリケーションコンテキストからすべてのentityManagerオブジェクトを取得できる必要があります。どうやってやるの?

以下は機能しません。空のマップを返します。

Map<String,EntityManager> ems = ctx.getBeansOfType(EntityManager.class);
役に立ちましたか?

解決

電話してみてください

EntitiyManagerFactory factory = 
          (EntityManagerFactory) ctx.getBean("myEntityManagerFactoryBean")
EntityManager em = factory.createEntityManager();

「myentitymanagerfactorbean」があなたです LocalContainerEntityManagerFactoryBean

しかし、なぜあなたはそれが必要なのですか?

他のヒント

SpringJunit4ClassRunnerを使用しています

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:jndiContext-mock.xml", 
                                    "classpath:spring/testContext.xml" })

テスト中のクレーゼは、模擬コンテキストを介して注入されます。これにより、注入によりエンティティマネージャーが得られます。

@PersistenceContext
protected HibernateEntityManager entityManager;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top