M
M
Miron2020-05-30 12:20:42
Java
Miron, 2020-05-30 12:20:42

How can I make transactions work through CGLIB so that I can call the transaction method inside the class?

Configuration:

<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <!-- (this dependency is defined somewhere else) -->
   <property name="dataSource" ref="dataSource"/>
</bean>
  
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/springjdbc?serverTimezone=UTC"/>
  <property name="username" value="root"/>
  <property name="password" value="1234"/>
</bean>


Class:

@Component
public class SomeNumbersMySQLDao{
  public JdbcTemplate jdbcTemplate;
  
  @Autowired
  public SomeNumbersMySQLDao self;
  
  @Autowired
  public SomeNumbersMySQLDao(DataSource dataSource){
    jdbcTemplate = new JdbcTemplate(dataSource);
  }
  
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
    SomeNumbersMySQLDao dao = context.getBean("someNumbersMySQLDao", SomeNumbersMySQLDao.class);
    
    dao.cleanTable();
    dao.outer(123);
    //dao.printTable();
  }
  
  @Transactional(propagation=Propagation.REQUIRED)
  public void outer(int number) {
    System.out.println(TransactionSynchronizationManager.isActualTransactionActive());
    jdbcTemplate.update("INSERT INTO someNumbers (number) VALUES (?)", new Object[] {number});
    self.withNever(number);
  }

  @Transactional(propagation=Propagation.NEVER)
  public void withNever(int numberToInsertInInnerMethod) {
    System.out.println(TransactionSynchronizationManager.isActualTransactionActive());
    jdbcTemplate.update("INSERT INTO someNumbers (number) VALUES (?)", new Object[] {numberToInsertInInnerMethod});
    jdbcTemplate.update("asdfghjkl;'qwertyuiop[]zxcvbnm,./");
  }
}


And it will work. Conclusion:


true
Exception in thread "main" org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation 'never'


However, I need to be able to call not the method of the embedded class, but the method of the class itself from within. That is, not self.withNever(number) , but withNever(number) . What do I need to add to the config file so that I can achieve this
effect?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question