#Transactional not working with Spring Boot and JDBC - java

My service should save data to a parent and child database tables, and rollback when an error ocurrs. I've tried forcing an error, using a hardcoded RuntimeException, and found the transaction gets commited no matter what.
What I'm I missing?
I'm using Spring Boot 2, including the spring-boot-starter-jdbc dependency.
Database is Oracle 11g.
Main configuration:
#SpringBootApplication
#EnableTransactionManagement
public class MyApplication extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Service layer:
#Service
public class MyBean {
private final NamedParameterJdbcTemplate jdbcTemplate;
private final MyDAO myDao;
#Autowired
public MyBean (NamedParameterJdbcTemplate jdbcTemplate, MyDAO myDao) {
this.jdbcTemplate = jdbcTemplate;
this.myDao= myDao;
}
#Override
#Transactional
public void saveData(...){
myDao.saveData(jdbcTemplate, ...);
}
}
DAO:
public void saveData(jdbcTemplate, ...){
saveDataInParentDatatable(jdbcTemplate, ...);
saveDataInChildDatatable(jdbcTemplate, ...);
}
private void saveDataInChildDatatable(jdbcTemplate, ...){
throw new RuntimeException();
}

I faced a similar issue. I'm assuming that you were calling the MyBean.saveData method at MyBean's another method.
After searching, trying and failing a lot, I found this link: http://ignaciosuay.com/why-is-spring-ignoring-transactional/
In it, it's explained that when the invoked method is in the same class where is it invoked, the #Transactional annotation is ignored. The Spring explanation for it is:
“In proxy mode (which is the default), only external method calls
coming in through the proxy are intercepted. This means that
self-invocation, in effect, a method within the target object calling
another method of the target object, will not lead to an actual
transaction at runtime even if the invoked method is marked with
#Transactional. Also, the proxy must be fully initialized to provide
the expected behaviour so you should not rely on this feature in your
initialization code, i.e. #PostConstruct.”
So I created another class to encapsulate my DAO method calling, used its method instead and it worked.
So for this case, it could be something like:
MyBean:
#Service
public class MyBean {
MyBean2 bean2;
public void saveData(...){
bean2.saveData(jdbcTemplate, ...);
}
}
MyBean2:
#Service
public class MyBean2 {
private final NamedParameterJdbcTemplate jdbcTemplate;
private final MyDAO myDao;
#Autowired
public MyBean2 (NamedParameterJdbcTemplate jdbcTemplate, MyDAO myDao) {
this.jdbcTemplate = jdbcTemplate;
this.myDao= myDao;
}
#Override
#Transactional
public void saveData(...){
myDao.saveData(jdbcTemplate, ...);
}
}

try this:
#Transactional(propagation = Propagation.MANDATORY, rollbackFor = Exception.class)

recommended use:
#Transactional(rollbackFor = {Exception.class, RuntimeException.class})

Related

How to write spring boot unit test for a method which calls another #Async method inside it?

I need to write integration test for "processEvent" method which calls a #Async method inside it. I tried writing a test for this method, but the issue was it did not save the Student object to the DB. However removing #Async annotation allows me to save the object. I want to know how should I write Test cases for this method, eliminating the #Async issue. I want to save the student object while testing. I have attached my code and below.
Here is the ClassA and it has the method I want to test.
#Service
public class ClassA {
private final ConfigurationProcessor<Student> configurationProcessor;
#Autowired
public ClassA(ConfigurationProcessor<Student> configurationProcessor) {
this.configurationProcessor = configurationProcessor;
}
public void processEvent(Configuration configuration) {
configurationProcessor.process(configuration);
}
}
This is the interface ConfigurationProcessor class
public interface ConfigurationProcessor<T> {
void process(Configuration configuration);
}
And this is its Impl class
#Service
public class ConfigurationProcessoeStudents10Impl implements ConfigurationProcessor<Student> {
private final StudentRepository studentRepository;
#Autowired
public ConfigurationProcessoeStudents10Impl(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
#Override
#Async
public void process(Configuration configuration) {
studentRepository.save(Student.builder().Name(configuration.name).Age(configuration.age));
}
}
This is the Test I have written so far.
#EnableAutoConfiguration
#SpringBootTest
public class AudienceC10IT {
#Autowired
ClassA classA;
#Test
#Tag("VerifyProcess")
#DisplayName("Verify kafka event consumer from configuration manager")
void verifyProcess(){
Configuration configuration = new Configuration("lal",12);
classA.processEvent(configuration);
}
}
If you have have set up a ThreadPoolTaskExecutor bean you can Autowire it in your test.
Then, after you call your async method, you can await the termination.
Then you can check for the expected behaviour / result.
Something like this:
#Autowired
private ThreadPoolTaskExecutor asyncTaskExecutor;
#Test
void test() {
callAsyncMethod();
boolean terminated = asyncTaskExecutor.getThreadPoolExecutor().awaitTermination(1, TimeUnit.SECONDS);
assertAsyncBehaviour();
}

#Transactional on class and getters/setters in #Autowired

when my code went through a code review, an error was pointed out.
code for example:
#Component
#Transactional
public class ClassA {
private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public method1() {
//some logic with transaction
}
...
public methodN() {
//some logic with transaction
}
}
I want everything method (method1...methodN) to be transactional.
But then, setter also in transactional. And the code-reviewers said it was wrong (pointed out the error).
But I don't understand why it's bad. What problems can be when using the transactional on the class (and setter also)?

how to get transaction support in Spring boot with Solr?

I'm using Spring Boot with Solr.
I can see Spring-tx in my resolved dependencies.
When I call a #Transactional annotated method in a Spring bean,
a) at runtime, i don't see any signs of it being wrapped in any transaction management proxy, and
b) when the method throws a RuntimeException the data is not rolledback.
The email/phone repositories and just interfaces that extend
org.springframework.data.solr.repository.SolrCrudRepository
What am i missing?
At have the method annotated #Transactional in both the interface and the implementation, just in case ;-)
public interface MyServiceInterface {
#Transactional
public CreateDetailsResponse createAllDetails(
final CreateDetailsRequest createDetailsRequest) throws BusinessException;
}
public class MyService implements MyServiceInterface {
#Autowired
private EmailRepository emailRepository;
#Autowired
private EmailRepository phoneRepository;
#Transactional
public CreateDetailsResponse createAllDetails(
final CreateDetailsRequest createDetailsRequest) throws BusinessException {
//method below calls emailRepository.save(emailDocument)
saveEmail();
//method below is supposed to call phoneRepository.save(phoneDocument)
//but throws RuntimeException before save is called
savePhone();
}
//...
}
#Configuration
#EnableSolrRepositories(basePackages = "com.....repository", multicoreSupport = true,
considerNestedRepositories = true, repositoryBaseClass = SoftCommitSimpleSolrRepository.class)
#EnableAutoConfiguration
public class ConsumersServiceConfiguration {
//...
#Bean
public MyServiceInterface myService() {
return new MyService();
}
}
Supposedly Solr supports transactions:

Service class not updating database when called within Service Class

I am working on Java Spring MVC project. When the Controller calls the method in ServiceImpl class (updateAttempt()) which in turn calls DAOImpl class, the update happens and I see the updated data in DB.
But when the loadUserByUserName (which is present in ServiceImpl class) calls updateAttempt() method in same ServiceImpl class, it doesn't throw any error or exception, but data never gets updated in DB.
PersonController.java
#Controller
#SessionAttributes({ "mob_Number"})
public class PersonController implements Observer, InitializingBean{
private static final Logger logger = LoggerFactory.getLogger(PersonController.class);
private PersonService personService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
public PersonController(PersonService personService){
this.personService = personService;
}
public PersonController(){
}
#RequestMapping(value="/submitVerificationCode",method = RequestMethod.POST, headers = "Accept=application/json")
#ResponseBody
public String submitVerificationCode(#RequestBody String json){
......
this.personService.update_User_Verification_AttemptCount(userVer.getMobile_Number(), no_Attempts);
//this call updates the data in DB
}
}
PersonServiceImpl.java
#Service
public class PersonServiceImpl implements PersonService, UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);
private PersonDAO personDAO;
private PersonService personService;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
#Autowired
private Observer observe;
#Override
#Transactional
public void update_User_Verification_AttemptCount(String mobile_number, int count){
this.personDAO.update_User_Verification_AttemptCount(mobile_number, count);
}
#Override
#Transactional
public UserDetails loadUserByUsername(String mobile_Number)
throws UsernameNotFoundException {
this.update_User_Verification_AttemptCount(mobile_Number, no_Attempts); //but this call doesn't update the data in DB
this.getUserDetails() //but this call returns data from DB
}
PersonDAOImpl.java
#Repository
public class PersonDAOImpl implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void update_User_Verification_VerCode(String mob_number, String verCode, Timestamp currentTimestamp){
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createQuery("update UserVerification set ver_Code=:verCode, sent_Time=:currentTimestamp where mobile_Number=:mob_Number");
query.setParameter("verCode", verCode);
query.setParameter("currentTimestamp", currentTimestamp);
query.setParameter("mob_Number", mob_number);
query.executeUpdate();
session.flush();
}
}
NOTE: the get methods residing in ServiceImpl(which does select) also return values properly when the get methods called from loadUserByUsername.
That is beacause your transaction does not commit when you call the methods inside the same service.
The problem there is that Spring enriches the bean with transaction behaviour by wrapping the bean inside the proxy and adding the behaviour to it. The proxy however is always created around the interface, so calling a method with this keyword will not propagate the desired behaviour.
a proper solution would be to repeat the dao call so to avoid the call of the same service method
#Transactional
public UserDetails loadUserByUsername(String mobile_Number)
throws UsernameNotFoundException {
this.personDAO.update_User_Verification_AttemptCount(mobile_number, count);
this.getUserDetails() //but this call returns data from DB
}
One other (hacky thing) that you can do is, since you already have a personService inside PersonServiceImpl, is to, first make sure that its injected, so add #Autowired
#Autowired private PersonService personService;
and than make a call through interface e.g.
personService.update_User_Verification_AttemptCount(mobile_Number, no_Attempts);
personService.getUserDetails()

Mocking Spring bean's method behavior breaks aspects

I searched SO and found bunch of other questions that looked similar but not exactly, so I'll ask another one.
I have Spring application and say I created custom aspect (looking for CatchMe annotation) to log exceptions in a specific way. I want to test the aspect by mocking the behavior of one of my Spring #Service class's method so it throws exception when it is called. Then in another method, annotated with my custom annotation #CatchMe, I call the first method. What I expect to happen is the exception to get logged. Unfortunatelly the exception is thrown but the aspect is not triggered. So how can I make the aspect to get triggered in this test using Mockito?
Note: I've checked those (plus a bunch more):
Unit testing Spring #Around AOP methods
Spring Aspect not triggered in unit test
Spring: cannot inject a mock into class annotated with the #Aspect annotation
but most of them are Controller related and not Service related and I want to test only the service.
The Test
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {BeanConfig.class})
public class MyServiceTest {
#Autowired
#InjectMocks
private MyService service;
#Mock
private MyServiceDependency serviceDep;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(service, "serviceDep", serviceDep);
}
#Test
public void test() {
when(serviceDep.process()).thenAnswer(new Answer<Object>() {
#Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
throw new Exception("Sample message.");
}
});
service.execute();
}
}
Services
#Service
public class MyService {
#Autowired
private MyServiceDependency serviceDep;
#CatchMe
public void execute() {
serviceDep.process();
}
}
#Service
public class MyServiceDependency {
public Object process() {
// may throw exception here
}
}
Configuration and Aspect
#Configuration
#EnableAspectJAutoProxy
#ComponentScan(basePackages = {"com.example.services"})
public class BeanConfig { .. }
#Aspect
#Component
public class CatchMeAspect {
#Around("#annotation(CatchMe)")
public Object catchMe(final ProceedingJoinPoint pjp) throws Throwable {
try {
pjp.proceed();
} catch (Throwable t) {
// fency log
}
}
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface CatchMe {}
EDIT: The functionality works but I want to verify it with the test.
Actually it is working as expected, however you are running in a side effect of proxy based AOP, especially class based proxies in this case.
Currently you are setting the field on the proxy and not on the actual object inside the proxy. Which is what you actually want. To obtain the actual instance use AopTestUtils.getUltimateTargetObject and then use that in the ReflectionTestUtils.setField method.
#Autowired
#InjectMocks
private MyService service;
#Mock
private MyServiceDependency serviceDep;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
MyService serviceToInject = AopTestUtils.getUltimateTargetObject(service);
ReflectionTestUtils.setField(serviceToInject, "serviceDep", serviceDep);
}
However I think that approach is wrong, when you start messing around like this there is a better way. Simply use Spring to inject the mock. Create a specific #Configuration class for this test case. Make it a internal public static class and for the dependency add a mocked #Bean.
#Configuration
#Import(BeanConfig.class)
public static class TestBeanConfig {
#Bean
public MyServiceDependency myServiceDependency() {
return Mockito.mock(MyServiceDependency.class);
}
}
Now in your test class you can simply #Autowire both beans and not need to use reflection or whatever to set dependencies.
#RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest {
#Autowired
private MyService service;
#Autowired
private MyServiceDependency serviceDep;
#Test
public void test() {
when(serviceDep.process()).thenAnswer(new Answer<Object>() {
#Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
throw new Exception("Sample message.");
}
});
service.execute();
}
}
Which will take care of the correct dependencies.
I had the same problem as #nyxz and this is intentional, see https://github.com/spring-projects/spring-boot/issues/7243.
Inspired by #M. Deinum following solution worked for me with Spring Boot 2.3.4.RELEASE and JUnit 5.
We will just provide a mocked bean without #MockedBean
#SpringBootTest
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class MyServiceTest {
#Autowired
private MyService service;
#Test
public void test() {
service.execute();
}
static class TestBeanConfig {
#Bean
#Primary
public MyServiceDependency myServiceDependency() {
MyServiceDependency myServiceDependency = Mockito.mock(MyServiceDependency.class)
// Add behavior of mocked bean here
return myServiceDependency;
}
}
}

Categories