I am implementing Spring old declarative TX technique
Here is my Target DAO Object:
neccesary imports..
public class UserDAOImpl extends JdbcDaoSupport {
public void add(int id, String name, Float salary){
System.out.println("add");
String SQL = "insert into User_Details (id, name, salary) values (?, ?, ?)";
getJdbcTemplate().update(SQL, id, name, salary);
getJdbcTemplate().update(SQL, id, name, salary);
getJdbcTemplate().update(SQL, id, name, salary);
throw new java.lang.RuntimeException("Exception occurs :)");
}
}
applicationContext.xml:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="add">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="userDetailProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="userDetailDAOImpl" />
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="userDetailDAOImpl" class="com.gagan.dao.UserDAOImpl">
<property name="dataSource" ref="dataSource" />
Main Class:
imports..
public class SpringTxTestCase {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDAOImpl ud=(UserDAOImpl)context.getBean("userDetailProxy");
ud.add(101,"Rahul", 1233.6f);
}
}
When i execute my Application i got this error:
Exception in thread “main” java.lang.ClassCastException: $Proxy0 cannot be cast to com.gagan.dao.UserDAOImpl
at SpringTxTestCase.main(SpringTxTestCase.java:14)
I have properly configured org.springframework.aop.framework.ProxyFactoryBean pointing to my com.gagan.dao.UserDAOImpl in applicationContext.xml but i am confused why i got ClassCastException error.
Thanks in advance,
Gagan
Using Spring to proxy your DAO impl class doesn’t yield an instance of the impl class. It yields something that implements the same interfaces as that class. Therefore you can never cast it to the impl class, only to the interfaces. That’s because Spring uses JDK dynamic proxies under the hood (by default). Since you don’t actually have a DAO interface, your proxy is pretty much useless to you. Add an interface to the DAO and refer to it via the interface.
Update: Oh, I should also note that the DAO is almost never the right place for transaction boundaries. They belong in your “service” layer except in a few, rare cases because a transaction reflects a unit of business work, not a unit of persistence work.