Введение Entitymanager через XML и не аннотации

То, что я пытаюсь сделать, вводят через XML почти тот же путь, который сделан через @PersistenceContext аннотацию. Я нуждаюсь в этом из-за факта, у меня есть различные менеджеры по объекту, которых я должен ввести в тот же ДАО. Базы данных зеркально отражают друг друга, и у меня был бы 1 базовый класс, и для экземпляров того базового класса затем создают несколько классов именно так, я могу использовать @PersistenceContext аннотацию.

Вот мой пример. Это - то, что я делаю теперь, и это работает.

public class ItemDaoImpl {
 protected EntityManager entityManager;

 public List<Item> getItems() {
     Query query = entityManager.createQuery("select i from Item i");
  List<Item> s = (List<Item>)query.getResultList();
  return s; 
 }
 public void setEntityManger(EntityManager entityManager) {
  this.entityManager = entityManager;
 }
}

@Repository(value = "itemDaoStore2")
public class ItemDaoImplStore2 extends ItemDaoImpl {

 @PersistenceContext(unitName = "persistence_unit_2")
 public void setEntityManger(EntityManager entityManager) {
  this.entityManager = entityManager;
 }
}

@Repository(value = "itemDaoStore1")
public class ItemDaoImplStore1 extends ItemDaoImpl {

 @PersistenceContext(unitName = "persistence_unit_1")
 public void setEntityManger(EntityManager entityManager) {
  this.entityManager = entityManager;
 }
}

TransactionManagers, EntityManagers определяются ниже...

<!-- Registers Spring's standard post-processors for annotation-based configuration like @Repository -->
<context:annotation-config />

<!-- For @Transactional annotations -->
<tx:annotation-driven transaction-manager="transactionManager1"  />
<tx:annotation-driven transaction-manager="transactionManager2"  />

<!-- This makes Spring perform @PersistenceContext/@PersitenceUnit injection: -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

<!-- Drives transactions using local JPA APIs -->
<bean id="transactionManager1" class="org.springframework.orm.jpa.JpaTransactionManager">
 <property name="entityManagerFactory" ref="entityManagerFactory1" />
</bean>

<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
 <property name="entityManagerFactory" ref="entityManagerFactory2" />
</bean>

<bean id="entityManagerFactory1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 <property name="persistenceUnitName" value="persistence_unit_1"/>
...
</bean>

<bean id="entityManagerFactory2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 <property name="persistenceUnitName" value="persistence_unit_2"/>
...
</bean>

То, что я хочу сделать, не должно создавать классы ItemDaoImplStore2 или ItemDaoImplStore1. Я хочу иметь их как экземпляры ItemDaoImpl через xml вместо этого. Я не знаю, как ввести entitymanager правильно все же. Я хочу моделировать аннотирование этого как аннотация 'Репозитория', и я также хочу смочь указать, какой entityManager ввести единицей персистентности называют. Я хочу что-то подобное ниже использования XML вместо этого.

 <!-- Somehow annotate this instance as a @Repository annotation -->
 <bean id="itemDaoStore1" class="ItemDaoImpl">
  <!-- Does not work since it is a LocalContainerEntityManagerFactoryBean-->
  <!-- Also I would perfer to do it the same way PersistenceContext works
   and only provide the persistence unit name.  I would like to be
   able to specify persistence_unit_1-->
  <property name="entityManager"  ref="entityManagerFactory1"/> 
 </bean>

  <!-- Somehow annotate this instance as a @Repository annotation -->
 <bean id="itemDaoStore2" class="ItemDaoImpl">
  <!-- Does not work since it is a LocalContainerEntityManagerFactoryBean-->
  <!-- Also I would perfer to do it the same way PersistenceContext works
   and only provide the persistence unit name.  I would like to be
   able to specify persistence_unit_2-->
  <property name="entityManager"  ref="entityManagerFactory2"/> 
 </bean>
11
задан user355543 1 June 2010 в 16:09
поделиться

1 ответ

Используйте SharedEntityManagerBean - он создает общий EntityManager для EntityManagerFactory так же, как @PersistenceContext:

<bean id="itemDaoStore1" class="ItemDaoImpl"> 
    <property name="entityManager">
        <bean class = "org.springframework.orm.jpa.support.SharedEntityManagerBean">
            <property name = "entityManagerFactory" ref="entityManagerFactory1"/>  
        </bean>
    </property>
</bean>
14
ответ дан 3 December 2019 в 06:45
поделиться
Другие вопросы по тегам:

Похожие вопросы: