Skip to content

Instantly share code, notes, and snippets.

@chaoyangnz
Last active March 21, 2016 09:58
Show Gist options
  • Save chaoyangnz/ccd6418865c8843d87e6 to your computer and use it in GitHub Desktop.
Save chaoyangnz/ccd6418865c8843d87e6 to your computer and use it in GitHub Desktop.
public class ActivejdbcTransactionManager extends DataSourceTransactionManager {
@Override
protected Object doGetTransaction() throws TransactionException {
Object txObject = super.doGetTransaction();
Method getConnectionHolder = ReflectionUtils.findMethod(txObject.getClass(), "getConnectionHolder");
ConnectionHolder connectionHolder = (ConnectionHolder)ReflectionUtils.invokeMethod(getConnectionHolder, txObject);
Connection connection;
if(connectionHolder == null) {
try {
connection = this.getDataSource().getConnection();
} catch (SQLException ex) {
throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
}
connectionHolder = new ConnectionHolder(connection);
Method setConnectionHolder = ReflectionUtils.findMethod(txObject.getClass(), "setConnectionHolder", ConnectionHolder.class);
ReflectionUtils.invokeMethod(setConnectionHolder, txObject, connectionHolder);
} else {
connection = connectionHolder.getConnection();
}
Method attach = ReflectionUtils.findMethod(ConnectionsAccess.class, "attach", String.class, Connection.class, String.class);
attach.setAccessible(true);
ReflectionUtils.invokeMethod(attach, null, "default", connection, "");
return txObject;
}
}
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root"/>
<property name="password" value="" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" />
<bean id="transactionManager" class="activejdbc.ActivejdbcTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment