java123999
java123999

Reputation: 7394

Using LocalContainerEntityManagerFactoryBean to create a session?

I am using Spring for the first time. Is it possible to use LocalContainerEntityManagerFactoryBean in order to create something similar to a hibernate session?

I am familiar with creating a hibernate session from hibernate.cfg.xml and also from entityManagerFactory in JPA.

But how do I use LocalContainerEntityManagerFactoryBean in order to be able to carry out transactions against my database?

Upvotes: 1

Views: 3887

Answers (1)

Yair Harel
Yair Harel

Reputation: 441

you will have to define jpa transaction manager which will be configured to your LocalContainerEntityManagerFactoryBean, for example :

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



<bean id="entityManagerFactory"

        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="enginePU" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaProperties">
           <props>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
                <prop key="hibernate.default_schema">dbo</prop>
                <prop key="hibernate.default_catalog">ab</prop>
           </props>
        </property>
      </bean>

then if you configured the transaction to be annotation driven :

<tx:annotation-driven />

you can use the entityManager in your daos like this :

    @PersistenceContext
    protected EntityManager entityManager;


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void persist(Object o) throws IOException {
         entityManager.persist(o);
    }

Hope it helps.

Upvotes: 1

Related Questions