weblogic jndi datasource issue with spring application - spring

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.

Related

Spring session factory is always null for multiple datasources

I am trying to #Autowire multiple Hibernate SessionFactory inside my application through Spring 4 SessionFactory DI. Only one Datasource(epi) is getting injected properly but the other two Datasources SessionFactory values are always null.
Two of them are oracle database and the other one is DB2. I am not sure what I am doing wrong.
Here is my spring-Datasource.xml
<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="epiStageDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver"/>
<property name="url" value="" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="epi"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="eveDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<!-- Session factory for EPI db -->
<bean id="episessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="epi" />
<property name="packagesToScan">
<list>
<value>edu.eve.model</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>
<!-- EVE DS SESSION FACTORY -->
<bean id="eveSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="eveDS" />
<property name="packagesToScan">
<list>
<value>edu.eve.model</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>
<!-- Session factory for Stage DS db -->
<bean id="stageDsSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="epiStageDS" />
<property name="packagesToScan">
<list>
<value>edu.eve.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
<prop key="hibernate.show_sql">${hibernate.db2.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.db2.format_sql:false}</prop>
</props>
</property>
</bean>
<bean id="epiTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="episessionFactory" />
</bean>
<bean id="eveTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="eveSessionFactory" />
</bean>
<bean id="stageDsTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="stageDsSessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
Here are the classes in which I am autowiring SessionFactory.
Below sessionFactory is getting injected perfectly.
#Transactional("epiTransactionManager")
public class EpiBaseService {
#Autowired
#Qualifier("episessionFactory")
private SessionFactory sessionFactory;
Autowired sessionFactory value are always null for below DS.
#Transactional("stageDsTransactionManager")
public class StageDsBaseService {
#Autowired
#Qualifier("stageDsSessionFactory")
private SessionFactory sessionFactory;
#Transactional("eveTransactionManager")
public class EveBaseService {
#Autowired
#Qualifier("eveSessionFactory")
private SessionFactory sessionFactory;
Please tell me what i am missing here.
I know what I was doing wrong. I was creating a new object of service class rather than #Autowiring inside the spring controller. I was doing this in order to make sure that my sessionfactory is not null but looks like that's not the correct way to do it. You have to use the Spring IOC container to inject the service class in your controller. Now all the sessionFactories are properly connected to specified datasources.

Spring transaction does not start

Environment: Eclipse Keppler, jetty 7.5.1,
Spring 3.2.1, Hibernate 4.2.5, Oracle 11
Problem: hibernate entity saves does not apply to database physically
Cause of problem may be: no active transaction
Question: Why does not transaction start?
Note: if I change openSession() to getCurrentSession(), everything works. Transaction starts & entity saves to DB physically.
GenericDaoImpl:
#Transactional(propagation = Propagation.REQUIRED, readOnly = false,
value = "transactionManager")
public abstract class GenericDaoImpl<T, ID extends Serializable> implements GenericDao<T, ID> {
private Class<T> persistentClass;
protected SessionFactory sessionFactory;
#Override
public T addEntity(T entity) {
Session session = null;
try {
session = sessionFactory.openSession();
session.save(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null){
Transaction t = session.getTransaction();
System.out.println("Transaction().isActive()......." + session.getTransaction().isActive());
System.out.println("before: session.isOpen() " + session.isOpen() + " trx wasCommitted " + t.wasCommitted());
session.close();
System.out.println("after: session.isOpen() " + session.isOpen() + " trx wasCommitted" + t.wasCommitted());
}
}
return entity;
}
UserDaoImpl extending GenericDaoImpl:
#Component
#Scope("prototype")
#Transactional(propagation = Propagation.REQUIRED, readOnly = false, value = "transactionManager")
public class UserDaoImpl extends GenericDaoImpl<User, Long> implements UserDao {
.
.
}
After following code executed called:
userDao.addEntity(user);
logs printed below:
Transaction().isActive().......false
before: session.isOpen() true trx wasCommitted false
after: session.isOpen() false trx wasCommittedfalse
transaction logs:
[2016-07-15 10:42:04,567][DEBUG] Adding transactional method 'addEntity' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; 'transactionManager'
databaseContext.xml:
<bean class="com.blabla.dao.local.implementations.UserDaoImpl"
scope="prototype" name="userDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan"
value="com.blabla.model.local,com.blabla.model.authorization, com.blabla.model.authentication" />
<property name="entityInterceptor">
<bean class="com.blabla.listeners.EntityInterceptor" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.transaction.flush_before_completion">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
<prop key="hibernate.connection.driver_class">${jdbc.driver}</prop>
<prop key="hibernate.connection.url">${jdbc.url}</prop>
<prop key="hibernate.connection.username">${jdbc.user}</prop>
<prop key="hibernate.connection.password">${jdbc.password}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
In your example it's pretty much obvious that spring handles hibernate session and transaction:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
So you cannot use this:
session = sessionFactory.openSession();
Because you are opening new hibernate session and spring does not know nothing about this.
Using: sessionFactory.getCurrentSession() means that spring will handle everything behind the scene with your proper configuration.

java.sql.SQLException: ORA-06576: not a valid function or procedure name

When saveDepartment() is invoked, I am getting exception mentioned in the title. After searching for solution for a while I came up with another similar post on stackoverflow which doesn't match the problem scenario I am facing.
Dao class:
#Repository
public class DepartmentDaoImpl implements DepartmentDao {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public void saveDepartment(Department department) {
Session session = sessionFactory.getCurrentSession();
session.save(department);
}
}
Bean configuration section for hibernate:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="net.therap.domain.tmp"/>
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Any suggestion or solution regarding the problem is appreciated.
ORA-06576 error code and oracle11g tag are suggesting you're using Oracle 11g Database.
Hibernate's Oracle10gDialect is compatible with that version, so you should use following dialect configuration:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="net.therap.domain.tmp"/>
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

Spring transactions doesn't work with Oracle Express

I have a simple standalone application to test transaction management with Spring.
Have Oracle Express Edition.
Run the following to enable XA
grant select on sys.dba_pending_transactions to user_test;
grant select on sys.pending_trans$ to user_test;
grant select on sys.dba_2pc_pending to user_test;
grant execute on sys.dbms_system to user_test;
My Java code is pretty much as follow:
public class DbUpdater
{
private static final ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring_transactions.xml"});
private static Logger log = LoggerFactory.getLogger(DbUpdater.class);
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void updateData() {
IMasterDAO ds1 = context.getBean("masterDao", IMasterDAO.class);
log.info("Insert using ds1");
ds1.insert("insert into users values(?,?)", "user1", "John Hamilton");
log.info("Insert using ds1 finished successfully");
throw new RuntimeException("A runtime exception");
}
}
So all the idea is too see transaction rolling back.
I run with several configuration examples and record is committed all the time.
No rollback is performed. No errors nothing, only expected
Exception in thread "main" java.lang.RuntimeException: A runtime exception
at com.test.spring.transation.DbUpdater.updateData(DbUpdater.java:22)
My last config is this:
<bean id="txManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="bitronixTransactionManager" />
<property name="userTransaction" ref="bitronixTransactionManager" />
</bean>
<bean id="btmConfig" factory-method="getConfiguration"
class="bitronix.tm.TransactionManagerServices">
<property name="serverId" value="spring-btm" />
</bean>
<bean id="bitronixTransactionManager" factory-method="getTransactionManager"
class="bitronix.tm.TransactionManagerServices"
depends-on="btmConfig,dataSource"
destroy-method="shutdown" />
<bean id="dataSource" class="bitronix.tm.resource.jdbc.PoolingDataSource"
init-method="init" destroy-method="close">
<property name="className" value="oracle.jdbc.xa.client.OracleXADataSource"/>
<property name="uniqueName" value="myOracleDataSource"/>
<property name="minPoolSize" value="0"/>
<property name="maxPoolSize" value="5"/>
<property name="allowLocalTransactions" value="true"/>
<property name="testQuery" value="select sysdate from dual"/>
<property name="driverProperties">
<props>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
<prop key="URL">${jdbc.url}</prop>
</props>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="masterDao" class="com.test.spring.transation.MasterDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
The JDBC template being instantiated via supplied data source, seems to work with its own transaction [there by the automatic begin and commit transaction]. The exception is thrown after that which operates in seperate commit/rollback cycle and hence you see that the writes persisted. To verify it, you can move the code to throw exception in MasterDAO class and examine rollback.

Spring, eclipselink, compass integration

I went through several articles and configured the following, but i can see some problems with transaction management. Please let me know whether i'm using compass correctly in the below configurations:
in Spring-config:
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean class="org.compass.spring.support.CompassContextBeanPostProcessor"/>
<bean id="compass" class="org.compass.spring.LocalCompassBean">
<property name="classMappings">
<list>
<value>......</value>
<value>......</value>
<value>......</value>
</list>
</property>
<property name="compassSettings">
<props>
<prop key="compass.engine.connection">file:///usr/local/lucene</prop>
<prop key="compass.transaction.factory">
org.compass.spring.transaction.SpringSyncTransactionFactory
</prop>
</props>
</property>
<property name="transactionManager" ref="transactionManager"/>
</bean>
in compass code:
private CompassSession session;
#CompassContext
protected void setCompassSession(CompassSession session) {
this.session = session;
}
public void index(Coupon coupon) throws AppException{
try {
session.save(coupon);
} catch (CompassException exception) {
logger.debug("Error in coupon indexing: "+ exception.getMessage());
}
}
in Service Layer:
#Transactional
public void saveCoupon(Coupon coupon) throws AppException{
Coupon savedCoupon = dbCouponDAO.saveCoupon(coupon); // saves to db through eclipselink
nonDbCouponDAO.index(savedCoupon); // indexes in compass
}
As per my understanding, transaction manager configured to eclipselink in spring can be used as compass transaction manager too, and both eclipselink and compass operations can be used in a single unit as i have mentioned in service layer.
Please let me know if i'm doing anything wrong here.
Thanks.
Try to add this,
<!-- Search Manager using Comass abstractions. -->
<bean class="org.compass.spring.support.CompassContextBeanPostProcessor"/>
<bean id="compass" class="org.compass.spring.LocalCompassBean">
<property name="compassSettings">
<props>
<prop key="compass.engine.connection">file://${user.home}/indexes</prop>
<prop key="compass.transaction.factory">org.compass.spring.transaction.SpringSyncTransactionFactory</prop>
</props>
</property>
<property name="classMappings">
<list>
<value>MyEntity</value>
</list>
</property>
<property name="transactionManager">
<ref local="transactionManager" />
</property>
</bean>
<bean id="jpaGpsDevice" class="org.compass.gps.device.jpa.JpaGpsDevice">
<property name="name">
<value>jpaDevice</value>
</property>
<property name="entityManagerFactory">
<ref local="entityManagerFactory" />
</property>
<property name="nativeExtractor">
<bean class="org.compass.gps.device.jpa.extractor.SpringNativeJpaExtractor" />
</property>
</bean>
<bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps" init-method="start" destroy-method="stop">
<property name="compass">
<ref bean="compass" />
</property>
<property name="gpsDevices">
<list>
<ref bean="jpaGpsDevice" />
</list>
</property>
</bean>
<!-- COMPASS END -->
Let me know if this helps.

Resources