I run into strange problem while developing application using Spring (3.0.5), Hibernate (3.6.0) and Wicket (1.4.14). The problem is: i cannot save or modify any object into
a) You are defining both a Hibernate SessionFactory
and a JPA EntitymanagerFactory
. Which is it going to be? Either use Hibernate's Session API or JPA's Entitymanager API with Hibernate as provider, but not both.
b) You have defined a HibernateTransactionManager
, but since you are using EntityManager
in your code, you need a JpaTransactionManager
instead:
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean
Here's a commented version of your applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans (...)>
<context:component-scan base-package="pl.m4ks.comics"/>
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:8889/comics" />
<property name="username" value="root"/>
<property name="password" value="root" />
</bean>
<!-- use either this: -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="main" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- or this -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="packagesToScan">
<value>pl.m4ks.comics</value>
</property>
</bean>
<!-- (but not both) -->
<!-- this is correct for AnnotationSessionFactoryBean, but not if you use
LocalContainerEntityManagerFactoryBean -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- not necessary, <context:annotation-config /> automatically includes this -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
</beans>
And a design note: DAOs shouldn't be transactional. You should use a service layer that manages the transactions. See this question (and many others) for reference.
Have you tried setting hibernate.connection.autocommit=true in hibernate config? That would solve the problem. But how efficient the approach is what you have to figure out.
you need to call following method on EntityManager
flush()
To make actual save in database