Thursday, March 28, 2024
HomeJavaThe best way to use @EnableTransactionManagement in Spring Framework and Spring Boot?...

The best way to use @EnableTransactionManagement in Spring Framework and Spring Boot? Instance Tutorial


Spring Boot has quite a bit many annotations inside its framework that an individual can use. If you’re looking for one, you’ve got come to the suitable place. Evidently, these annotations are important for constructing a Spring Boot net utility. Right this moment we’ll take a look at an annotation that’s extensively used for transaction administration in spring. So, what is the wait?! Let’s begin! However, earlier than leaping into the ocean of spring, let’s first perceive what a transaction means in spring and what it signifies. A transaction is utilized in Spring JPA which communicates to the database. everyone knows what a transaction represents on a database stage. If not, no worries! allow us to all recall.

What’s a Transaction?

A database transaction is a set of operations which might be thought-about as in the event that they had been a single piece of labor. These actions ought to both end utterly or don’t have any impression. To guarantee knowledge integrity and consistency, transaction administration is an important side of RDBMS-based company functions.

The next 4 necessary qualities could also be used to characterize the thought of transactions:

  • A transaction ought to be seen as a single unit of operation, which suggests the whole sequence of actions is both profitable or failed.
  • Consistency refers back to the database’s referential integrity, in addition to the usage of distinctive main keys in tables.
  • Isolation A number of transactions with the identical knowledge set could also be processed on the similar time. To keep away from knowledge corruption, every transaction ought to be separated from the others.
  • Sturdiness Upon completion of a transaction, the outcomes should be made everlasting and can’t be faraway from the database as a result of a system failure.
  • Use the start transaction command to start out the transaction.
  • SQL queries could also be used to carry out quite a few delete, replace, and insert operations.
  • If all the actions are profitable, commit them; in any other case, roll again all of them.
On prime of many underlying transaction administration APIs, the Spring framework affords an summary layer. By introducing transaction capabilities to POJOs, Spring’s transaction help seeks to supply a substitute for EJB transactions. 

Each declarative and programmatic transaction administration is supported by Spring. Though EJBs require the usage of an utility server, Spring transaction administration could also be dealt with with out one.

@EnableTransactionManagement annotation in Spring 

Just like the help offered in Spring’s <tx:*> XML namespace, this property permits Spring’s annotation-driven transaction administration performance. To arrange basic, crucial transaction administration or reactive transaction administration, make the most of @Configuration lessons.

1. The annotation-driven transaction administration performance is enabled by the @EnableTransactionManagement attribute. @Configuration lessons reap the benefits of it.

2. The @EnableTransactionManagement property configures both classical, crucial, or reactive transaction administration.

3. Within the configuration class, assemble a PlatformTransactionManager bean for crucial transaction administration.

4. Within the configuration class, assemble a ReactiveTransactionManager bean for reactive transaction administration.

5. The XML namespace <tx:annotation-driven/> is just like the @EnableTransactionManagement annotation.

That is all theoretical, let’s deep dive into code and perceive the way it works. Let’s create a spring challenge and a config class to deal with all of the configurations of our challenge.

How is @EnableTransactionManagement used in Spring and Spring  Boot ? Example Tutorial

Discover beneath the pattern configuration class. you possibly can add the imports on the go in your ide.

@Configuration
@EnableTransactionManagement
public class AppConfig {
@Bean
public Cricketer cricketer() {
return new Cricketer();
}

@Bean
public HibernateTemplate hibTemp() {
return new HibernateTemplate(sessionFactory(), true);
}

@Bean
public SessionFactory sessionFactory() {
SessionFactory sf =
new AnnotationConfiguration().configure()
.buildSessionFactory();
return sf;
}
@Bean
public HibernateTransactionManager hibTransMan(){
return new HibernateTransactionManager(sessionFactory());
}
}

Now, let’s create a Cricketer object class for a similar.

@Entity
public class Cricketer implements Serializable {
personal static closing lengthy serialVersionUID = 1L;
@Id
personal int id;
personal String identify;
public Cricketer(){
}
public Cricketer(int id,String identify){
this.id=id;
this.identify=identify;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return identify;
}
public void setName(String identify) {
this.identify = identify;
}
}

Now, let’s create a pattern class to check our code,

public class AppTest {
public static void fundamental(String[] args) {
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext();

ctx.register(AppConfig.class);
ctx.refresh();

HibernateTemplate hibtemp= ctx.getBean(HibernateTemplate.class);
Cricketer c1=
new Cricketer(1,“Virat”);
hibtemp.persist(c1);

Cricketer c2= new Cricketer(2,“Rohit”);
hibtemp.save(c2);

}
}

Now, for those who guys are questioning what is going on, simply have a look. The @EnableTransactionManagement annotation permits the processing of transactions in spring with the usage of the @Transactional annotation. you should utilize @Transactional annotation solely in case you have @EnableTransactionalManagement utilized in your app-config class or within the XML configuration file.
@EnableTransactionManagement Example in Spring

To cite the identical from spring docs, the beneath configuration file is similar because the XML file. Take a look.

config file : 

@Configuration
@EnableTransactionManagement
public class AppConfig {

@Bean
public FooRepository fooRepository() {

return new JdbcFooRepository(dataSource());
}

@Bean
public DataSource dataSource() {

}

@Bean
public PlatformTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource());
}
}

XML file : 

<beans>

<tx:annotation-driven/>

<bean id=“fooRepository” class=“com.foo.JdbcFooRepository”>
<constructor-arg ref=“dataSource”/>
</bean>

<bean id=“dataSource” class=“com.vendor.VendorDataSource”/>

<bean id=“transactionManager” class=“org.sfwk…DataSourceTransactionManager”>
<constructor-arg ref=“dataSource”/>
</bean>

</beans>

@EnableTransactionManagement is chargeable for registering the mandatory Spring elements that energy annotation-driven transaction administration, such because the TransactionInterceptor and the proxy- or AspectJ-based recommendation that weaves the interceptor into the decision stack when JdbcFooRepository’s @Transactional strategies are invoked, in each of the situations above.

The identify of the TransactionManager bean differs considerably between the 2 examples: The identify is “txManager” (per the identify of the tactic) within the @Bean case and “transactionManager” within the XML case. By default, @EnableTransactionManagement appears for a bean known as “transactionManager,” however it’s extra versatile; it’s going to fall again to a by-type lookup for any TransactionManager bean within the container.

Conclusion

On this article, we discovered about alternative ways of enabling the transaction together with the @EnableTransactionManagement annotation, how it’s used and the place and the best way to use it. We additionally noticed the equal XML configuration file. Now, you guys are all set and able to attempt it your self and use the facility of spring in your initiatives! 

Different Spring Framework articles you might wish to discover 

Thanks for studying this text thus far. If you happen to like these Spring
@EnableTransactionManagement annotation tutorials and examples then, please share them together with your
mates and colleagues.
In case you have any questions or suggestions, then please drop a be aware.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments