Using TransactionProxyFactoryBean with Spring and Hibernate - java

I have an old project that I'm trying to upgrade to spring 4 / hibernate 4.
We use this approach to configuring our transactions.
That is to say, in XML we define a transaction manager like:
<bean id="abstractTransactionProxy"
abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="hibernateTransactionManager"/>
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_SUPPORTS,readOnly</prop>
</props>
</property>
and
<bean id="MySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="configLocation" value="WEB-INF/hibernate.cfg.xml" />
</bean>
and then each of our service beans are defined like:
<bean id="customerService" parent="abstractTransactionProxy">
<property name="target" ref="customerTarget"/>
<property name="personDAO" ref="personDAO" />
</bean>
and the DAOs are defined like:
<alias name="personDaoImpl" alias="personDAO"/>
<bean id="personDaoImpl"
class="com.foo.bar.hibernate.PersonDaoImpl">
<property name="sessionFactory" ref="MySessionFactory" />
</bean>
PersonDaoImpl (and all the other DAOs) have many methods that look like this (all of the DAOs extend HibernateDaoSupport):
public List<Person> getPersonByCriteria(final String criteria) {
List<Person> results =
(List<Person>) this.getHibernateTemplate().executeFind(new HibernateCallback<List<Person>>(){
public List<Person> doInHibernate(Session session) throws HibernateException, SQLException {
List<Person> results = (List<Person>) session.createQuery(MYSQLHERE).setString("criteria", criteria).list();
return results;
}
});
return results;
}
Now, the problem I Face at this point is getting rid of our dependency on extending our DAOs from HibernateDaoSupport, and by extension, on using it's HibernateTemplate helper object.
Here's the steps I've taken:
Simply remove them from the DAO methods - don't extend HibernateDaoSupport, remove the HibernateTemplate callback. This looks like:
public List<Person> getPersonByCriteria(final String criteria) {
List<Person> results = (List<Person>) getSessionFactory().getCurrentSession().createQuery(MYSQLHERE).setString("criteria", criteria).list();
return results;
}
Of course this gives me compile-time errors because 'getSessionFactory' was part of the base class 'HibernateDaoSupport' which I just removed.
So I implemented a 'MyHibernateDaoSupport' Class, and had my DAO extend that instead. It looks like:
public class MyHibernateDaoSupport {
private SessionFactory sessionFactory;
protected Session session;
protected static Logger logger = Logger.getLogger(MyHibernateDaoSupport.class);
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
session = this.sessionFactory.getCurrentSession();
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
public Session getHibernateTemplate() {
session = this.sessionFactory.getCurrentSession();
return session;
}
public MyHibernateDaoSupport() {
}
}
Now I can build, deploy and run and I hit this error message:
No session available in this thread
How can I make this work?
In simple terms, what was the 'hibernateCallback()', and it's anoymous inner class actually doing?
How can I make my project's transactions work as before, without using HibernateDaoSupport and HibernateTemplate classes?
I've tried tagging my 'CustomerService' (the business logic object that calls 'PersonDao') with #transactional but (A) I see the same error regardless and (B) I'd really prefer to be able to do this programmatically, to reduce the scale of changes to the way the code works now. I also tried putting the transactions at the DAO level instead, and met the same issue.
Apologies if that was way too much detail for the Stack overflow format.

You need to inject the SessionFactory into your DAO classes:
#Repository
public class PersonDAOImpl implements PersonDAO {
#Autowired
private SessionFactory sessionFactory;
public List<Person> getPersonByCriteria(final String criteria) {
List<Person> results = (List<Person>) getSessionFactory().getCurrentSession().createQuery(MYSQLHERE).setString("criteria", criteria).list();
return results;
}
}
Add #Transactional to your service methods
Add HibernateTransactionManager
Instruct Spring to use declarative transactions:
<tx:annotation-driven transaction-manager="transactionManager"/>
Make sure you use LocalSessionFactoryBean for creating the SessionFactory
Here's a detailed step-by-step tutorial for configuring Spring and Hibernate 4

Related

How to connect Two Database MySQL and MongoDB in the same project? Is it possible?

Currently I'm using Hibernate(MySQL) with Spring, the configuration is running fine for me, but once I configured another configuration mongo-config.xml file and trying to run a test case with mongodb it's showing Error creating bean with name .... from first configuration.
Below is my mongo-config.xml
<context:annotation-config />
<context:component-scan base-package="com.test.mongo" />
<context:property-placeholder location="classpath:mongo-dao.properties" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="driverClassName" value="${spring.datasource.driverClassName}" />
<property name="host" value="${spring.data.mongodb.host}" />
<property name="port" value="${spring.data.mongodb.port}" />
<property name="databaseName" value="${spring.data.mongodb.database}" />
and my first configuration for hibernate is looks like something
<context:component-scan base-package="com.hb.dao" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.jdbc.driverClassName}" />
<property name="url" value="${db.jdbc.url}" />
<property name="username" value="${db.jdbc.username}" />
<property name="password" value="${db.jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.hb..dao.domain.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
And the stack trace is
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accessProfileDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.soe.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
Here is my test Class-
public class MongoQuestionsTest extends BaseDaoMongoTest{
private static final Logger logger = LogManager.getLogger(MongoQuestionsTest.class);
#Autowired
private MongoTestDao mongoTestDaoImpl;
#Test
public void saveQuestions(){
MongoQuestions mongoQuestions = new MongoQuestions();
mongoQuestions.setUsername("Hi");
mongoQuestions.setPassword("Hello");
mongoTestDaoImpl.save(mongoQuestions);
logger.debug("Mongo User Set with id " + mongoQuestions.getId());
}
and **BaseDaoMongoTest**---
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:/mongo-config-test.xml"})
public class BaseDaoMongoTest {
}
And in MongoTestDaoImpl class I just Auto-wired MongoTemplate and calling save() method that's it.
I'm not sure whether this is the best solution. But, it worked for me.
If you have two relational databases using Jpa module, then I would suggest you to create entity and transaction manager beans to read each datasource config. Refer the below link for the above use case.
springboot always read data from primary datasource
As you wish to have a combination of SQL and NoSQL, I would create entity and transcation manager beans for MySQL database as it works well with Jpa. And leave as-is configuration for Mongo(configs read directly from application.properties).
MySQLConfiguration datasource config class :
#Configuration
#PropertySource("classpath:persistence-multiple-db.properties")
#EnableJpaRepositories(basePackages = "com.springdata.dao.mysql", entityManagerFactoryRef = "mysqlEntityManager", transactionManagerRef = "mysqlTransactionManager")
public class MySQLConfiguration {
#Autowired
private Environment env;
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean mysqlEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(myMySQLDataSource());
em.setPackagesToScan(new String[] { "com.springdata.models" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
#Bean
#Primary
public DataSource myMySQLDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.mysql.jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("spring.mysql.jdbc.url"));
dataSource.setUsername(env.getProperty("spring.mysql.user"));
dataSource.setPassword(env.getProperty("spring.mysql.pass"));
return dataSource;
}
#Bean
#Primary
public PlatformTransactionManager mysqlTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(mysqlEntityManager().getObject());
return transactionManager;
}
Above datasource config params are read from classpath:persistence-multiple-db.properties file in the classpath.
# mysql jdbc connections
spring.mysql.jdbc.driverClassName=com.mysql.jdbc.Driver
spring.mysql.jdbc.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false
spring.mysql.user=root
spring.mysql.pass=password1
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
The above configuration, should be suffice to deal MySQL datasource. To have mongo configuration in your project, add the below lines to application.properties.
# mongo configuration
spring.data.mongodb.uri=mongodb://localhost
spring.data.mongodb.database=test
Springboot will automatically create the necessary mongo datasource beans and keeps them readily available for spring container to use.
Now, create repository interfaces for both MySQL and Mongo datasources.
MyMongoRepository interface:
#Transactional
public interface MyMongoRepository extends MongoRepository<Users, String>{
}
MySQLRepository interface:
#Transactional
public interface MySQLRepository extends JpaRepository<Users, String>{
}
Users pojo class :
#Entity
#Table(name = "users")
#Document(collection="users")
#Data
public class Users {
#Id
#javax.persistence.Id
private String id;
private String name;
private Integer age;
}
Have added below annotations to enable mongorepositoreis and for component scan to springboot main class.
#SpringBootApplication
#ComponentScan(basePackages = { "com.springdata" })
#EnableMongoRepositories(basePackages={"com.springdata.dao.mongo"})
public class SpringbootmysqlmongoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmysqlmongoApplication.class, args);
}
}
Finally, some code to test.
MyRepositoryImpl class:
#Service
public class MyRepositoryImpl {
#Autowired
private MyMongoRepository myMongoRepository;
#Autowired
private MySQLRepository mySQLRepository;
#PostConstruct
public void extractUsers(){
myMongoRepository.findAll().forEach((user) -> System.out.println("user name from mongo is : "+user.getName()));
mySQLRepository.findAll().forEach((user) -> System.out.println("User name from mysql is : "+user.getName()));
}
}
Have created users table in mysql test database and users collection in mongo test database.
Lastly, have uploaded my code to git repository.
https://github.com/harshavmb/springbootmysqlmongo

Spring JPA Hibernate handle large databases

I am new to JPA, Hibernate as well as Spring. Currently I am creating a spring web service which work with a database with a large number of tables. To access those tables I have created separate class annotating #Entity. Then I created a generic DAO class as all my entities need similar operations.
#Transactional
public class GenericJpaDao<T, ID extends Serializable> {
private Class<T> persistentClass;
private EntityManager entityManager;
public GenericJpaDao(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
protected EntityManager getEntityManager() {
return entityManager;
}
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Class<T> getPersistentClass() {
return persistentClass;
}
#Transactional(readOnly = true)
public T findById(ID id) {
T entity = (T) getEntityManager().find(getPersistentClass(), id);
return entity;
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<T> findAll() {
return getEntityManager().createQuery("select x from " + getPersistentClass().getSimpleName() + " x").getResultList();
}
public T save(T entity) {
getEntityManager().persist(entity);
return entity;
}
public T update(T entity) {
T mergedEntity = getEntityManager().merge(entity);
return mergedEntity;
}
public void delete(T entity) {
entity = getEntityManager().merge(entity);
getEntityManager().remove(entity);
}
public void flush() {
getEntityManager().flush();
}
}
Now I tried to instantiate this GenericJpaDao in the code with relevant Entitiy Class as the persistentClass. But then I could not find a way to set the entitiyManager as I am configuring it via datasource-config.xml as
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
<property name="persistenceUnitName" value="hibernatePersistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
So according to what I understood from the samples available I need to create separate DAO classes for all my entity classes and instantiate them in spring-ws-servlet.xml.
<bean id="testDao" class="com.sample.dao.TestDao" />
<bean id="service"
class="com.sample.service.DefaultService">
<property name="testDao" ref="testDao" />
</bean>
I think this will be a problem in the long run as I need to have two separated classes for each table in the database, instaintiating them in the xml, keep track of all of them at my service class. Is there any method to overcome this or any best practice available?
You wont need to create a specific DAO for each of your classes.
But you will have to remove the constructor and change your method signatures to include the needed persistentClass (or an instance where you call getClass on).
Basically you need to remove the persistentClass property and change the methods to use the class dynamically from the generic parameter of type T or Class.
That way you have ONE spring managed DAO which is able to handle all of your entities.

How to inject EntityManager in EntityListeners

I need to inject EntityManager in EntityListener class so that I can perform CRUD operation on it.
POJO:
#Entity
#EntityListner(AuditLogging.class)
class User
{
//Getter / setter of properties
}
AuditLogging (Listner class)
public class AuditInterceptor
{
#PersistenceContext
EntityManager entityManager;
public void setEntityManager(EntityManager entityManager)
{
this.entityManager = entityManager;
}
#PrePersist
public void prePersist(Object obj)
{
// Here I want to use ENTITY manager object so that I can perform CRUD operation
// with prePersist coming object.
entityManager.unwrap(Session.class).save(obj);
// But I am getting NULL POINTER EXCEPTION for entity manager object
}
}
JDBC-CONFIg.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<property name="packagesToScan" value="com.XXXXX.entity" />
<property name="jpaProperties">
</bean>
<!-- Datasource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver.classname}" />
<property name="jdbcUrl" value="${jdbc.url}" />
</bean>
<!-- transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
EntityListener is not managed by any of the container.EntityListeners are instanciated by JPA, so Spring does not have an opportunity to inject EntityManager.
My question is, how we can inject inject EntityManager in EntityListener class so that I can perform CRUD operation on it ???
I have faced a similar problem where I was trying to create history records for an entity using EntityListeners.
In order to resolve this problem, I have created utility class BeanUtil with a static method to get the bean and used this util class to get bean inside my Entitylistener class
#Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
Now we can call BeanUtil.getBean() to get the bean of any type
public class FileEntityListener {
#PrePersist
public void prePersist(File target) {
perform(target, INSERTED);
}
#Transactional(MANDATORY)
private void perform(File target, Action action) {
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new FileHistory(target, action));
}
}
We can use this BeanUtil class to get any spring managed bean from anywhere, To know more you can read my article JPA Auditing: Persisting Audit Logs Automatically using EntityListeners.
Anyways, I got this done by getting entityManager reference from EntityManagerFactory bean which is configured in my jdbc-config.xml. But again this is not what I wanted. I wanted to work around with #PersistenceContext.
#Autowired
EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
entityManager=entityManagerFactory.createEntityManager();
this.entityManagerFactory = entityManagerFactory;
}
Here are few notes that we need to keep in mind:
We can't inject an EntityManager into an EntityListener (through
#PersistenceContext). EntityListener is not managed by any of the
containers
#PersistenceContext class cannot be static. So we cant
attain the instance while class loading.
EntityListeners are
instantiated by JPA, so Spring does not have an opportunity to
inject EntityManager
Well, the first solution which came into my mind is a little "hack", but should work.
public class AuditInterceptor {
static setEntityManager emf;
#Autowired
public void setEntityManagerFactory(EntityManager emf) {
AuditInterceptor.emf = emf;
}
#PrePersist
public void prePersist(Object obj) {
EntityManager entityManager = emf.getEntityManager();
// Here I want to use ENTITY manager object so that I can perform CRUD operation
// with prePersist coming object.
entityManager.unwrap(Session.class).save(obj);
// But I am getting NULL POINTER EXCEPTION for entity manager object
}
}
Inside of your code use EntityManager entityManager = emf.getEntityManager()
Declare your AuditInterceptor as a spring bean (#Component with component-scan or define AuditorInterceptor as a bean)
I used a ThreadLocal to pass the Spring Application Context which contains EntityManager around. Though I am not sure if it is safe Is it safe to pass in the Spring Application Context into a ThreadLocal associated with a request? but so far it is working for me.
The listener can be modified to have autowiring like this. However this needs to be done on on the handlers and not the constructor (doing it on the constructor seems less predictable). You are also not limited to the EntityManager but you have access to the whole context.
#Autowired
private EntityManager entityManager;
#Autowired
private MyDao myDao;
#PrePersist
public void pre() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
Objects.requireNotNull(myDao);
myDao.doSomething();
}

Why can't I retrieve the entities I've just persisted?

I've got this web service that basically queries the database and returns all persisted entities. For testing purposes, I've created a TestDataManager that persists 2 example entities after Spring context is loaded (BTW, I'm using JAX-WS, Spring, Hibernate and HSQLDB).
My TestDataManager looks like this:
#Component
public class TestDataManager {
#Resource
private SessionFactory sf;
#PostConstruct
#Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void insertTestData(){
sf.openSession();
sf.openSession().beginTransaction();
sf.openSession().persist(new Site("site one"));
sf.openSession().persist(new Site("site two"));
sf.openSession().flush();
}
}
My JAX-WS endpoint looks like this:
#WebService
public class SmartBrickEndpoint {
#Resource
private WebServiceContext context;
public Set<Site> getSitesForUser(String user){
return getSiteService().findByUser(new User(user));
}
private ISiteService getSiteService(){
ServletContext servletContext = (ServletContext) context.getMessageContext().get("javax.xml.ws.servlet.context");
return (ISiteService) BeanRetriever.getBean(servletContext, ISiteService.class);
}
}
This my Service class:
#Component
#Transactional(readOnly = true)
public class SiteService implements ISiteService {
#Resource
private ISiteDao siteDao;
#Override
public Set<Site> findByUser(User user) {
return siteDao.findByUser(user);
}
}
This is my DAO:
#Component
#Transactional(readOnly = true)
public class SiteDao implements ISiteDao {
#Resource
private SessionFactory sessionFactory;
#Override
public Set<Site> findByUser(User user) {
Set<Site> sites = new LinkedHashSet<Site>(sessionFactory.getCurrentSession().createCriteria(Site.class).list());
return sites;
}
}
This is my applicationContext.xml:
<context:annotation-config />
<context:component-scan base-package="br.unirio.wsimxp.dao"/>
<context:component-scan base-package="br.unirio.wsimxp.service"/>
<context:component-scan base-package="br.unirio.wsimxp.spring"/>
<bean id="applicationDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:file:sites"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="applicationDS" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.release_mode">on_close</prop>
<!--<prop key="hibernate.current_session_context_class">thread</prop>-->
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
This is what's going on now:
when the app is deployed, TestDataManager#insertTestData kicks-in (due to #PostConstruct) and persist does not raise any exception. I should have 2 entities in the DB by now.
Afterwards, I invoke the endpoint by a SOAP client, and the request goes all the way up to the DAO. The Hibernate invocation does not raise any exception, but the returned list is empty.
The odd thing is, in TestDataManager, if I switch from sf.openSession() to sf.getCurrentSession(), I get an error message: "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here".
What I am doing wrong here? Why is the query "not seeing" the persisted entities? Why do I need to invoke sf.openSession() on TestDataManager although it's annotated with #Transactional?
I have done some tests with hibernate.current_session_context_class=thread in application.xml, but then I just switch problems in each class. I'd like not needing to manually invoke sf.openSession() and leave that for Hibernate to take care.
Thanks a lot for any help!
I think you need to commit the transaction on insertTestData:
#PostConstruct
#Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void insertTestData(){
Session session = sf.openSession();
session.persist(new Site("site one"));
session.persist(new Site("site two"));
session.flush();
session.close();
}
(I use hibernate in jpa mode)
I think your transactional annotations are not intercepted properly. Have you specified the HibernateVendorAdapter? In jpa+hibernate the integration is not fully setuped without it! Most likely you are missing this declaration.
After you should be able to autowire directly the Session instead of the Factory.
As a side note. If you use opensession in your code at least call it only once and keep the session in a variable. Else you are always opening a new one on each call i believe.
#PostConstruct
public void insertTestData(){
Obejct o = new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
//Your code here
}
});
}
source: http://forum.springsource.org/showthread.php?58337-No-transaction-in-transactional-service-called-from-PostConstruct&p=194863#post194863

Transactions not working unless inside DAO

I have a problem with transactions in that annotating a service that calls a DAO with #Transactional throws an exception stating that the Session is not open. The only way I can get it working is by annotating the DAO with #Transactional. What on earth can be happening?
This is what I'd like to do but doesn't work:
class CustomerService {
private CustomerDao dao;
#Transactional
public void foo() {
int customerId = dao.getCustomer("fred");
}
}
class CustomerDao {
private HibernateTemplate hibernateTemplate;
public int getCustomer(String name) {
String sql = "SELECT {m.*} from Customers {m} where name=:name";
Query qry = getSession().createSQLQuery(sql).addEntity("m", Customer.class);
qry.setParameter("name", name);
qry.setCacheable(false);
List<Customer> list = qry.list();
return list.iterator().next().getId();
}
private Session getSession() {
return hibernateTemplate.getSessionFactory().getCurrentSession();
}
}
This is what I'm doing instead but would rather not have to:
class CustomerService {
private CustomerDao dao;
public Customer(CustomerDao dao) {
this.dao = dao;
}
public void foo() {
int customerId = dao.getCustomer("fred");
}
}
class CustomerDao {
private HibernateTemplate hibernateTemplate;
#Transactional
public int getCustomer(String name) {
String sql = "SELECT {m.*} from Customers {m} where name=:name";
Query qry = getSession().createSQLQuery(sql).addEntity("m", Customer.class);
qry.setParameter("name", name);
qry.setCacheable(false);
List<Customer> list = qry.list();
return list.iterator().next().getId();
}
private Session getSession() {
return hibernateTemplate.getSessionFactory().getCurrentSession();
}
}
The problem seems to be caused by the CustomerService being instantiated inside the constructor of a wrapper class, where the wrapper is declared in the Spring xml context file:
class AllServices {
private final CustomerService customerService;
private final OrderService orderService;
#Autowired
public AllServices(CustomerDao customerDao, OrderDao orderDao) {
this.customerService = new CustomerService(customerDao);
this.orderService = new OrderService(orderDao);
}
public CustomerService getCustomerService() {
return this.customerService;
}
public OrderService getOrderService() {
return this.orderService;
}
}
The spring file looks like this:
<context:annotation-config />
<import resource="classpath:db-spring-conf.xml"/>
<bean id="allServices" class="myPackage.AllServices" />
and the db-spring-conf:
<bean id="editorDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${versioning.db}" />
<property name="username" value="${versioning.user}" />
<property name="password" value="${versioning.pass}" />
</bean>
<tx:annotation-driven transaction-manager="editorTransactionManager"/>
<bean id="editorSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="editorDatasource"/>
<property name="exposeTransactionAwareSessionFactory">
<value>true</value>
</property>
<property name="annotatedClasses">
<list>
<value>myPackage.Order</value>
</list>
</property>
<property name="mappingResources">
<list>
<value>mappings/customer.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<!-- Enable Query Cache -->
<prop key="hibernate.cache.use_query_cache">false</prop>
<!-- Enable 2nd Level Cache -->
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
</props>
</property>
</bean>
<bean id="editorHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="editorSessionFactory"/>
</bean>
<bean id="editorTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="editorSessionFactory" />
</bean>
<!-- DAOs -->
<bean id="customerDao" class="myPackage.CustomerHibernateDao" />
<bean id="orderDao" class="myPackage.OrderHibernateDao" />
I've now moved the instantiation of CustomerService up to the Spring config file and everything works a treat. Do all classes using #Transactional have to be in the context file? Also in order to make it work I had to create an interface for CustomerService to prevent an exception whilst loading the context file - Could not generate CGLIB subclass of class
So, you identified the cause of problem - Spring's #Transactional support is an aspect, and aspects in Spring are applied only to the components managed by the Spring contrainer (though it can be changed, but it's an advanced feature for complex cases).
If you don't like declaring services in XML, you may take a look at other options to delcare Spring-managed components:
Classpath scanning
Java-based configuration (since Spring 3.x)
Regarding the problem with CGLIB proxies see 7.6 Proxying mechanisms - probably you don't have CGLIB implementation in the classpath.

Categories