How to configure Two Data Sources to single Transaction manager using Spring JTA,So that on the exception Both of the data sources get rolled back - spring

I would like to configure the two Data sources one is Oracle and one is My-SQL to the Transaction Manager in the Spring JTA to perform the 2 phase commit so that any one transaction of the any of the Data sources get failed and the spring JTA needs to perform the roll back on the both of the data sources
*Heard the atomikos can we used to configure this kind of scenarios
Please provide the some configuration codes are anything that would be useful in implementing this code *
Git url for the entire code:
https://github.com/mageshsrinivasulu/poc
spring-beans.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean class="org.springframework.beans.factory.config
.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:Application.properties" />
</bean>
<bean id="oracleSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="oracleDataSource" />
<property name="mappingResources">
<list>
<value>persons.hbm.xml </value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.autocommit">false</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">10</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
</props>
</property>
</bean>
<bean id="mysqlSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="mysqlDataSource" />
<property name="mappingResources">
<list>
<value>persons.hbm.xml </value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.autocommit">false</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">10</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
</props>
</property>
</bean>
<!-- Creating TransactionManager Bean, since JDBC we are creating of type
DataSourceTransactionManager -->
<bean id="oracleTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="oracleDataSource" />
</bean>
<bean id="mysqlTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="mysqlDataSource" />
</bean>
<bean id="oracleDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${oracle.hibernate.connection.driver_class}" />
<property name="url" value="${oracle.hibernate.connection.url}" />
<property name="username" value="${oracle.Username}" />
<property name="password" value="${oracle.Password}" />
</bean>
<bean id="mysqlDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.jdbc.driverClassName}" />
<property name="url" value="${mysql.hibernate.connection.url}" />
<property name="username" value="${mysql.Username}" />
<property name="password" value="${mysql.Password}" />
</bean>
<bean id="persons" class="com.bnym.aal.poc.spring_jta.Persons">
</bean>
<bean id="App" class="com.bnym.aal.poc.spring_jta.App">
<property name="springJtaDaoClass" ref="springJtaDaoClass" />
</bean>
<bean id="springJtaDaoClass" class="com.bnym.aal.poc.spring_jta.springJtaDaoClass">
<property name="oracleSessionFactory" ref="oracleSessionFactory" />
<property name="mysqlSessionFactory" ref="mysqlSessionFactory" />
<property name="oracleTransactionManager" ref="oracleTransactionManager" />
<property name="mysqlTransactionManager" ref="mysqlTransactionManager" />
<property name="persons" ref="persons" />
</bean>
springJtaDaoClass
import java.io.Serializable;
import java.util.List;
import javax.sql.DataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
package com.bnym.aal.poc.spring_jta;
public class springJtaDaoClass implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private static SessionFactory oracleSessionFactory;
private static SessionFactory mysqlSessionFactory;
private HibernateTemplate oracleJdbcTemplateObject;
private HibernateTemplate mysqlJdbcTemplateObject;
private static Persons persons;
public static SessionFactory getOracleSessionFactory() {
return oracleSessionFactory;
}
public void setOracleSessionFactory(SessionFactory oracleSessionFactory) {
springJtaDaoClass.oracleSessionFactory = oracleSessionFactory;
this.oracleJdbcTemplateObject=new HibernateTemplate(oracleSessionFactory);
}
public static SessionFactory getMysqlSessionFactory() {
return mysqlSessionFactory;
}
public void setMysqlSessionFactory(SessionFactory mysqlSessionFactory) {
springJtaDaoClass.mysqlSessionFactory = mysqlSessionFactory;
this.mysqlJdbcTemplateObject=new HibernateTemplate(mysqlSessionFactory);
}
public static PlatformTransactionManager oracleTransactionManager;
public static PlatformTransactionManager mysqlTransactionManager;
public static PlatformTransactionManager getOracleTransactionManager() {
return oracleTransactionManager;
}
public static void setOracleTransactionManager(PlatformTransactionManager
oracleTransactionManager) {
springJtaDaoClass.oracleTransactionManager = oracleTransactionManager;
}
public static PlatformTransactionManager getMysqlTransactionManager() {
return mysqlTransactionManager;
}
public static void setMysqlTransactionManager(PlatformTransactionManager
mysqlTransactionManager) {
springJtaDaoClass.mysqlTransactionManager = mysqlTransactionManager;
}
public static Persons getPersons() {
return persons;
}
public static void setPersons(Persons persons) {
springJtaDaoClass.persons = persons;
}
public void dbOracleAccess()
{
TransactionDefinition oracledef= new DefaultTransactionDefinition();
TransactionStatus oraclestatus =
oracleTransactionManager.getTransaction(oracledef);
try
{
Persons person1=getPersons().persons(1,"a","b","c","d");
oracleJdbcTemplateObject.save(person1);
oracleTransactionManager.commit(oraclestatus);
}
catch (DataAccessException e) {
System.out.println("Error in creating record, rolling back");
oracleTransactionManager.rollback(oraclestatus);
throw e;
}
}
public void dbMySqlAccess()
{
TransactionDefinition mysqldef= new DefaultTransactionDefinition();
TransactionStatus
mysqlstatus=mysqlTransactionManager.getTransaction(mysqldef);
try
{
Persons person2=getPersons().persons(2,"e","b","c","d");
mysqlJdbcTemplateObject.save(person2);
mysqlTransactionManager.commit(mysqlstatus);
}
catch (DataAccessException e) {
System.out.println("Error in creating record, rolling back");
mysqlTransactionManager.rollback(mysqlstatus);
throw e;
}
}
}

Below is the working code of the above stated issue:
Entire project for the Atomikos Transaction manager for the connecting the two data sources to the single transaction manager by out of box integration would be available in the below GIT url
https://github.com/mageshsrinivasulu/spring-jta.git
spring-beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:Application.properties" />
</bean>
<bean id="oracleSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="oraclesDataSource" />
<property name="mappingResources">
<list>
<value>persons.hbm.xml </value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<!-- <prop key="hibernate.autocommit">true</prop> <prop key="hibernate.connection.isolation">3</prop> -->
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.CMTTransactionFactory
</prop>
<prop key="hibernate.transaction.manager_lookup_class">
com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup
</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">10</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
</props>
</property>
</bean>
<bean id="mysqlSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="mysqlDataSource" />
<property name="mappingResources">
<list>
<value>persons.hbm.xml </value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- <prop key="hibernate.autocommit">ture</prop> <prop key="hibernate.connection.isolation">3</prop> -->
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.CMTTransactionFactory
</prop>
<prop key="hibernate.transaction.manager_lookup_class">
com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup
</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">10</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
</props>
</property>
</bean>
<tx:annotation-driven proxy-target-class="true" />
<tx:jta-transaction-manager
transaction-manager="atomikosTransactionManager" />
<tx:annotation-driven transaction-manager="atomikosTransactionManager"
proxy-target-class="true" />
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close">
<property name="forceShutdown" value="false" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction">
<property name="transactionTimeout" value="300" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager"
depends-on="atomikosTransactionManager,atomikosUserTransaction">
<property name="transactionManager" ref="atomikosTransactionManager" />
<property name="userTransaction" ref="atomikosUserTransaction" />
<property name="allowCustomIsolationLevels" value="true" />
</bean>
<bean id="mysqlDataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>mySqlDataSource</value>
</property>
<property name="xaDataSourceClassName">
<value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="databaseName">sys</prop>
<prop key="serverName">localhost</prop>
<prop key="port">3306</prop>
<prop key="user">root</prop>
<prop key="password">magesh123</prop>
<prop key="url">jdbc:mysql://localhost:3306/sys</prop>
</props>
</property>
<property name="minPoolSize">
<value>1</value>
</property>
</bean>
<bean id="oraclesDataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>OracleDataSource</value>
</property>
<property name="xaDataSourceClassName">
<value>oracle.jdbc.xa.client.OracleXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="databaseName">XE</prop>
<prop key="serverName">localhost</prop>
<!-- <prop key="port">1521</prop> -->
<prop key="user">system</prop>
<prop key="password">magesh123</prop>
<prop key="URL">jdbc:oracle:thin:#localhost:1521:XE</prop>
</props>
</property>
<property name="minPoolSize">
<value>1</value>
</property>
</bean>
<bean id="persons" class="com.bnym.aal.poc.spring_jta.Persons">
</bean>
<bean id="App" class="com.bnym.aal.poc.spring_jta.App">
<property name="springJtaDaoClass" ref="springJtaDaoClass" />
</bean>
<bean id="springJtaDaoClass" class="com.bnym.aal.poc.spring_jta.springJtaDaoClass">
<property name="oracleSessionFactory" ref="oracleSessionFactory" />
<property name="mysqlSessionFactory" ref="mysqlSessionFactory" />
<property name="atomikosTransactionManager" ref="transactionManager" />
<property name="persons" ref="persons" />
</bean>
springJtaDaoClass.java
package com.bnym.aal.poc.spring_jta;
import java.io.Serializable;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public class springJtaDaoClass implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static SessionFactory oracleSessionFactory;
private static SessionFactory mysqlSessionFactory;
private HibernateTemplate oracleJdbcTemplateObject;
private HibernateTemplate mysqlJdbcTemplateObject;
private static Persons persons;
public static SessionFactory getOracleSessionFactory() {
return oracleSessionFactory;
}
public void setOracleSessionFactory(SessionFactory oracleSessionFactory) {
springJtaDaoClass.oracleSessionFactory = oracleSessionFactory;
this.oracleJdbcTemplateObject = new
HibernateTemplate(oracleSessionFactory);
}
public static SessionFactory getMysqlSessionFactory() {
return mysqlSessionFactory;
}
public void setMysqlSessionFactory(SessionFactory mysqlSessionFactory) {
springJtaDaoClass.mysqlSessionFactory = mysqlSessionFactory;
this.mysqlJdbcTemplateObject = new
HibernateTemplate(mysqlSessionFactory);
}
public static PlatformTransactionManager atomikosTransactionManager;
public static PlatformTransactionManager getAtomikosTransactionManager() {
return atomikosTransactionManager;
}
public static void setAtomikosTransactionManager(PlatformTransactionManager
atomikosTransactionManager) {
springJtaDaoClass.atomikosTransactionManager =
atomikosTransactionManager;
}
public static Persons getPersons() {
return persons;
}
public static void setPersons(Persons persons) {
springJtaDaoClass.persons = persons;
}
#Transactional()
public void daoWrapper() throws Exception {
atomikosTransactionManager = getAtomikosTransactionManager();
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status =
atomikosTransactionManager.getTransaction(def);
Persons person1 = new Persons();
person1.persons(2, "a", "b", "c", "d");
try {
getMysqlSessionFactory().getCurrentSession().save(person1);
getOracleSessionFactory().getCurrentSession().save(person1);
atomikosTransactionManager.commit(status);
} catch (Exception e) {
System.out.println("Error in creating record, rolling back");
atomikosTransactionManager.rollback(status);
e.printStackTrace();
}
}
}

You can check out mine github link for full sample web application for Two Phase (2PC) Protocol demo which store data in MySQl database first and then in Oracle database and also maintain ACID if oracle database throw exception then roll back is also happen in MySql database
Git hub link for 2PC Sample Web application
Two Phase (2PC) demo application
I am not using 3rd party JTA provider instead i am using J2EE Compliant Application server JBOSS AS 7 for JTA service.

Related

Integration of Spring 5+ Hibernate 5 + Atomikos 4 + Tomcat Unable to locate current JTA transaction

I have tried many different solutions, but getting the exception:
org.hibernate.HibernateException: Unable to locate current JTA
transaction at
org.hibernate.context.internal.JTASessionContext.currentSession(JTASessionContext.java:75)
~[hibernate-core-5.2.12.Final.jar:5.2.12.Final] at
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:465)
~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
I am using Atomikos 4.0.4, Hibernate 5.2.12, Spring 5.0.2 and Tomcat.
How to configure Spring 5 + Hibernate 5
This is my configuration
application-context.xml
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="net.sf.ehcache.configurationResourceName">/ehcache/ehcache.xml</prop>
<prop key="hibernate.connection.datasource">java:/comp/env/jdbc/myoracle</prop>
<prop key="hibernate.transaction.jta.platform">cgaweb.common.atomikos.SpringJtaPlatformAdapter</prop>
<prop key="hibernate.max_fetch_depth">2</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="javax.persistence.transactionType">jta</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
<prop key="hibernate.mapping.precedence">class, hbm</prop>
<prop key="connection.driver_class">oracle.jdbc.OracleDriver</prop>
</props>
</property>
</bean>
<!-- jta transaction -->
<bean id="atomikosTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp" init-method="init" destroy-method="shutdownWait" >
<constructor-arg>
<props>
<prop key="com.atomikos.icatch.log_base_name">UserTransactionServiceImplog</prop>
</props>
</constructor-arg>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close" depends-on="atomikosTransactionService">
<property name="forceShutdown" value="true"/>
<property name="transactionTimeout" value="300" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp" depends-on="atomikosTransactionService">
<property name="TransactionTimeout" value="300"/>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="atomikosTransactionManager"></property>
<property name="userTransaction" ref="atomikosUserTransaction"></property>
<property name="allowCustomIsolationLevels" value="true"></property>
</bean>
<!-- Manager lookup-->
<bean id="springJtaPlatformAdapter" class="cgaweb.common.atomikos.SpringJtaPlatformAdapter">
<property name="jtaTransactionManager" ref="transactionManager" />
</bean>
<!-- post construct -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
the code of springJtaPlatformAdapter
public class SpringJtaPlatformAdapter extends AbstractJtaPlatform {
private static TransactionManager sTransactionManager;
private static UserTransaction sUserTransaction;
#Override
protected TransactionManager locateTransactionManager() {
return sTransactionManager;
}
#Override
protected UserTransaction locateUserTransaction() {
return sUserTransaction;
}
public void setJtaTransactionManager(JtaTransactionManager jtaTransactionManager) {
sTransactionManager = jtaTransactionManager.getTransactionManager();
sUserTransaction = jtaTransactionManager.getUserTransaction();
}
public void setTransactionManager(TransactionManager transactionManager) {
sTransactionManager = transactionManager;
}
public void setUserTransaction(UserTransaction userTransaction) {
sUserTransaction = userTransaction;
}
}
i am using tomcat, and i add the following lib :
transaction-jta-4.0.4.jar
transaction-jdbc.4.0.4.jar
transaction-hibernate4-4.0.jar
transaction-api-4.0.4.jar
transactions-4.0.4.jar
jta-1.1.jar
can you please help me to solve this issue ?
Thanks
The commercial edition of Atomikos contains built-in Tomcat integration and Hibernate 5 support:
https://www.atomikos.com/Main/ExtremeTransactionsFreeTrial
Alternatively, you can wait for the 5.0 release of TransactionsEssentials where Hibernate 5 demos would also be included. I will not have built-in Tomcat integration though.
Best regards

Exception in running spring hibernate application

Hi I Have implemented the spring and hibernate integration i have an exception while integrating the exceptions is:
Please Help Me to Solve This exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.springframework.context.support.AbstractRefreshableApplicationContext.createBeanFactory(AbstractRefreshableApplicationContext.java:194)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:127)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:465)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:395)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.InsertTest.main(InsertTest.java:14)
here is the xml file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="test.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
here is the sample program:
>
package test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Resource r=new ClassPathResource("test.xml");
// BeanFactory factory=new XmlBeanFactory(r);
ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)context.getBean("d");
Employee e=new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(50000);
dao.saveEmployee(e);
}
}
Just Remove The All Added JAR files and try Adding each Jar file Carefully wont add the already added jar files this will work i have tested and working for mine

Why is #PrePersist is not being invoked in Hibernate 5.2?

I just recently moved from Hibernate4 to Hibernate5. I have implemented #PrePersist on my entity bean but #PrePersist doesn't seem to be firing up.
I have searched around
https://github.com/hibernate/hibernate-orm/wiki/Migration-Guide---5.2
And on it it states
org.hibernate.SessionFactory now extends javax.persistence.EntityManagerFactory - temporarily it technically extends org.hibernate.jpa.HibernateEntityManagerFactory (which in turn extends javax.persistence.EntityManagerFactory) for backwards compatibility. HibernateEntityManagerFactory is deprecated.
So this means JPA annotation should work right?
My entity class looks like this
#Entity
#Table(name="books")
#Component
public class Book implements Serializable{
private static final long serialVersionUID = -2042607611480064259L;
#Id
#GeneratedValue
private int id;
#NotBlank
private String name;
#NotBlank
#Size(min=2, max=16)
private String ispn;
#DecimalMin(value = "0.1")
private double price;
private Timestamp dateCreated;
private Date datePublished;
#PrePersist
public void beforePersist() {
System.out.println("#PrePersist is called");
this.dateCreated = Timestamp.from(Instant.now());
}
applicationContext.xml (Hibernate configuration)
<!-- Connection Pool -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<property name="dataSourceProperties">
<props>
<prop key="url">jdbc:mysql://localhost:3306/sample</prop>
<prop key="user">sample</prop>
<prop key="password">sample</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"
destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- Hibernate Settings -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.id.new_generator_mappings">false</prop>
<prop key="hibernate.jdbc.time_zone">UTC</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="org.hibernate.jdbc">TRACE</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.app.books</value>
</list>
</property>
</bean>
Questions
Something wrong with how I implement #Prepersist?
Or perhaps my Hibernate configuration has some error?
Thank you

weblogic jndi datasource issue with spring application

I have created a oracle datasource in weblogic with the name jdbc/myDS.
Weblogic created a xml file in mydomain/config/jdbc and the configuration works from the weblogic admin console. Test connection is working. My spring context file details are:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/myDS"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<util:map>
<entry key="hibernate.hbm2ddl.auto" value="update" />
<entry key="hibernate.show_sql" value="true" />
</util:map>
</property>
</bean>
<bean id="myDAO" class ="com.example.MyDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
My Java class is:
public class MyDAOImpl implements MyDAO{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void persistPerson(Person person) {
Session session = getSessionFactory().openSession();
try {
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
}catch(HibernateException he) {
he.printStackTrace();
} finally {
session.close();
}
}
}
An error occurred during activation of changes, please see the log for
details.
Message icon - Error weblogic.application.ModuleException:
Message icon - Error While trying to lookup 'jdbc.myDS' didn't find subcontext 'jdbc'. Resolved ''; remaining name 'jdbc/myDS'
The following provides a Spring XML configuration to obtain a datasource by a JNDI name and inject it into Springs AnnotationSessionFactoryBean.
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/YourJndi"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="annotatedClasses">
<list>
<value>com.java.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
This example has been sucessfully tested on Weblogic 10.3.4 with Oracle 11g.

Bean is not getting initialized in Spring

Please find my codes below
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
And my applicationContext.xml is here
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref
bean="sessionFactory" />
</property>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>
/com/qantas/cardselector/model/config/TcerConfigItem.hbm.xml
</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.session_factory_name">
HibernateSessionFactory
</prop>
<prop
key="hibernate.transaction.manager_lookup_class">
org.hibernate.transaction.WeblogicTransactionManagerLookup
</prop>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</prop>
<prop key="hibernate.current_session_context_class">
jta
</prop>
<prop key="hibernate.connection.datasource">
salesDataSource
</prop>
<prop key="hibernate.connection.release_mode">
auto
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.use_outer_join">true</prop>
<prop key="hibernate.query.factory_class">
org.hibernate.hql.classic.ClassicQueryTranslatorFactory
</prop>
<prop key="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.query.substitutions">
toLowerCase=lower,toUpperCase=upper,
today=TRUNC(sysdate),now=sysdate,getDate=TRUNC
</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="InitialLoad" name="/InitialLoadAction"
class="com.qantas.cardselector.action.cardslist.CardsListAction">
<property name="cardManagementService"
ref="cardManagementService" />
</bean>
<bean id="CardsList" name="/cardsList"
class="com.qantas.cardselector.action.cardslist.CardsListAction">
<property name="cardManagementService"
ref="cardManagementService" />
</bean>
<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="cardManagementService" parent="transactionProxy">
<property name="target">
<bean class="com.qantas.cardselector.service.impl.CardManagementServiceImpl">
<property name="cardManagementDAO" ref="cardManagementDAO" />
</bean>
</property>
</bean>
<bean id="cardManagementDAO" class="com.qantas.cardselector.dao.impl.CardManagementDAOimpl">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
</beans>
and my action class is here
package com.qantas.cardselector.action.cardslist;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.qantas.cardselector.form.CardsListForm;
import com.qantas.cardselector.service.CardManagementService;
import com.qantas.cardselector.vo.SearchFilterVO;
public class CardsListAction extends Action {
public CardManagementService cardManagementService;
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
System.out.println("action started");
SearchFilterVO searchFilterVO =null;
if(getCardManagementService()!=null)
{
String returnvalue = getCardManagementService().retrieveParams(searchFilterVO);
System.out.println("returnvalue"+returnvalue);
}
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
e.printStackTrace();
}
return mapping.findForward("success");
}
public CardManagementService getCardManagementService() {
return cardManagementService;
}
public void setCardManagementService(CardManagementService cardManagementService) {
this.cardManagementService = cardManagementService;
}
}
this action class always throwing null pointer exceptions while calling service object as it shown in the code... please Can any one help...
Guys I have found answer for my question below,
have just added the piece of code in struts-config.xml
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="csntextConfigLocation" value="/WEB-INF/applicationContext.xml"/>
</plug-in>
And added an empty action-servlet.xml file

Resources