Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional wrapping 2 methods

I'm a Spring newby. I use the @Transactional annotation for my dao methods:

@Transactional
public Person getById(long id) {
    return new Person(jdbcTemplate.queryForMap(...));
}

@Transactional
public void save(Person person) {
    jdbcTemplate.update(...);
}

and I've set up the transaction manager like this:

<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

The problem is that when my client code calls dao.save(..) and then dao.getById(4) these happen in two separate transactions. How is it possible to wrap those 2 calls in the same database transaction? Ideally without doing it in a programmatic way.

thanks

like image 618
cherouvim Avatar asked Dec 13 '22 20:12

cherouvim


1 Answers

It is bad practice to put transactional attributes in DAO layer. Also, I am not sure why do you require transaction for getById method. Even if you want to use transaction then you need to specify propagation behaviour as REQUIRES_NEW for save and getById method.

like image 148
Rakesh Goyal Avatar answered Feb 16 '23 03:02

Rakesh Goyal