0% found this document useful (0 votes)
35 views

Springboot Annotations Quick Reference

This document provides a quick reference to common Spring Boot annotations like @SpringBootApplication, @ComponentScan, @RestController, @RequestMapping, @ExceptionHandler, and more. It describes what each annotation is used for and examples of how to use them in code.

Uploaded by

Akanksha Ojha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Springboot Annotations Quick Reference

This document provides a quick reference to common Spring Boot annotations like @SpringBootApplication, @ComponentScan, @RestController, @RequestMapping, @ExceptionHandler, and more. It describes what each annotation is used for and examples of how to use them in code.

Uploaded by

Akanksha Ojha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

14/04/2024, 19:33 Springboot Annotations Quick Reference

Articles People Learning Jobs

Springboot Annotations Quick


Reference
Suneel A. + Follow
Java J2EE Springboot Microservice Architecture Spring RESTful APIs
OOAD Architecture Design Development troubleshooting AWS Data
Engineering AWS Cloud Agile Methodology DevOps CI/CD
Published Mar 11, 2024

Following are some of the Springboot annotations for quick reference

1. @SpringBootApplication

Combination of below annotations

@ComponentScan

@EnableAutoConfiguration

@Configuration

2. @EnableAutoConfiguration

It configures spring boot application based on jar dependencies added in pom.xml,


For example, if any database jar is present, we do not have to configure the beans
related to that manually like data source bean etc.

3. @ComponentScan - for configuring the path where to scan for the beans,
default it scans current and sub-packages(base packages and base classes), we can
specify any path also where to scan for the beans

@ComponentScan(basePackages = "com.basepackage1 ")

Multiple base packages

@ComponentScan(basePackages = {"com.basepackage1", "com.basepackage2"})


Like Comment Share 6

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 1/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

4. @Configuration

It means we have defined beans in the annotated class so that spring IoC can load
them, third party class objects can be load as beans by adding @Bean annotation
on methods where that class bean is returned. The @Configuration annotation
marks a class as source of bean definitions, the life cycle of the beans defined in
this class are handled by spring IoC container.

Stereotype Annotations: These annotations are used to create spring beans


automatically, when added these annotations on any bean, spring will manage the
lifecycle of those beans. The derived annotation are more specific types that
denotes what specific role a particular component is going to play.

5. @Component

This is the base annotation and following annotations like @Service, @Controller,
@Repository are derived from the @Component annotation.

6. @Service

Denotes a service layer class where we can provide some business logic.

7. @RestController Vs @Controller

@Controller is generic type of controller like web controller, REST controller etc.,
It is typically used with annotations like @RequestMapping @ResponseBody

@RestController is a specific annotation that denotes a component as


RestController and we can use specific annotations like @GetMapping,
@PostMapping, @PutMapping, @DeleteMapping

While we use the @RequestMapping annotation which is again a generic


annotation and it can be used with all kinds of Http methods, we need pass the
request method explicitly, like RequestMethod.GET, POST etc.

RequestMetod is an enum that contains constants - GET, HEAD, POST, PUT,


PATCH, and DELETE, OPTIONS, TRACE

Also if we are using @Controller annotation, we need to explicitly provide


@ResponseBody annotation,

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 2/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

8. @ResponseBody annotation

it specifies that java object is serialized into JSON and put into the body of the
response

9. @RequestBody annotation

It is used to parse/deserialize incoming request body into a java object

10. The ResponseEntity<T> object represents whole HTTP Response i.e.,


response body, response headers, and status code etc. it also allows to add
headers and status code.

11. @GetMapping

This annotation maps HTTP GET request to a handler method, it is equivalent to


the @RequestMapping(method = RequestMethod.GET)

12. Likewise, there are @PostMapping,@PutMapping,@DeleteMapping,


@PatchMapping methods but for head and options methods there are no specific
annotations, the only option is to fall back to the @RequestMapping,

@RequestMapping(method = RequestMethod.HEAD)

@RequestMapping(method = RequestMethod.OPTIONS)

13. @RequestParam Vs @PathVariable Vs @QueryParam

@QueryParam is used to retrieve the value from the query string. for example,
the following request

/foo?id=1001

@GetMapping(“/foo”)

Public string getFoobyId(@RequestParam String id)

14. @PathVariable

This annotation is used to retrieve the value from URI path

For example /foo/{id}

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 3/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

@GetMapping(“/foo”)

Public string getFoobyId(@PathVariable String id)

15. @RequestParam

This annotation is used to extract input data that may be passed as a query, form
data, etc.

16. @RequestHeader

Request headers can be captured by using the name of the request header in the
following way

@GetMapping("/foo")

public ResponseEntity<String>
getFoo(@RequestHeader(HttpHeaders.ACCEPT_LANGUAGE) String language) {}

to capture all the request headers, there are two ways, the following code can be
used:

@GetMapping("/foo")

public ResponseEntity<String> getFoo(@RequestHeader Map<String, String>


headers) {

headers.forEach((key, value) -> {

});

OR

@GetMapping("/foo")

public ResponseEntity<String> fetFoo(@RequestHeader HttpHeaders headers) {}

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 4/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

Exception handling with @ControllerAdvice and @RestControllerAdvice and


@Exception handler

17. @ControllerAdvice

This is another specialization of @Component, to be used for classes that declare


@ExceptionHandler methods to be used across multiple controllers.

18. @RestControllerAdvice

This annotation is a combination of @ControllerAdvice + @ResponseBody

19. @ResponseStatus

This annotation is used to set the response status, it can be used in the exception
handler

@ResponseStatus(HttpStatus.NOT_FOUND)

public class UserNotFoundExecption extends RuntimeException {}

20. @ExceptionHandler

This annotation is used with specific handler classes or methods that handle
exceptions. It takes any of the Exception.class as an argument. Root exception
matching is preferred to the current exception and if there are multiple Controller
Advice Beans, @Order and @Priority annotations should be used to specify the
order and priority, lower value of order takes higher precedence.

For example:

@ExceptionHandler(Exception.class)

public final ResponseEntity<Object> handleAllExceptions(Exception ex,


WebRequest request) {}

@ExceptionHandler(UserNotFoundExecption.class)

public final ResponseEntity<Object> handleUserNotFoundException(Exception


ex, WebRequest request) {

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 5/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

FailureResponse failureResponse = new FailureResponse(new Date(),


ex.getMessage(),request.getDescription(false));

return new ResponseEntity<Object>(failureResponse, HttpStatus.NOT_FOUND);

21. @Autowired

It is used for automatic dependency injection of beans

22. @Qualifier

Spring resolves autowired entries by type. If there are more than one beans of
same type, the container throws NoUniqueBeanDefinitionException, as there is
ambiguity as to which bean to be injected. By including the @Qualifier annotation
we are specifying which specific implementation to be injected. The qualifier
name to be used is the one that is used in @Component

Alternatively, we can use @Primary annotation to mark a bean as primary and the
container injects that bean by default. If we add @Primary annotation to any of
the components, we need not add @Qualifier to all beans when we add second
bean instance.

23. @Lazy

Spring IoC container initializes all beans by default at the start up and this will
unnecessarily create a large number of objects including those that may not be
used immediately, this will occupy a lot of heap, by using the @Lazy annotation,
we are instructing the container to load the bean only on demand,

24. @Value

This annotation is used to inject property values into the bean from property files,
this is used in combination with @PropertyResource annotation

@Value("${dbConnectionString}")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 6/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

private String dbConnectionString;

Injecting default value as below:

If server.port property is not set, it will inject default value 8080.

@Value("${server.port:8080}")

private String port;

Also, we can specify the property files using @PropertySource file

@PropertySource("classpath:/com/abc/app.properties")

25. @ConfigurationProperties

This annotation is used to map or bind the entire external configuration values in .
properties or . yml files to Java objects

@Component

@PropertySource("classpath:xyz.properties")

@ConfigurationProperties

public class XYZProperties {

private int x;

private String y;

//getters and setters

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 7/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

26. Conditional annotations can be applied to any beans with @Component,


@Service, @Repository, or @Controller annotations

27. @ConditionalOnProperty – for example, to enable logging if the property


logging.enabled is set to true, and we can specify default value if it is not set

@Service

@ConditionalOnProperty(

value="logging.enabled",

havingValue = "true",

matchIfMissing = true)

class LoggingService {

28. @ConditionalOnExpression

@Service

@ConditionalOnExpression(

"${logging.enabled:true} and '${logging.level}'.equals('DEBUG')"

class LoggingService {

29. @Conditional

@Service

@Conditional(MyCondition.class)

public class MyBeanClass {

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 8/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

We can create a custom class by extending classes like Condition,


AnyNestedCondition etc, and use them with @Conditional annotation, like the
below, if the java version is 8

class MyCondition implements Condition {

@Override

public boolean matches(ConditionContext context, AnnotatedTypeMetadata


metadata) {

return JavaVersion.getJavaVersion().equals(JavaVersion.EIGHT);

30. @Profile

This annotation is used to load properties related to a particular environment like


dev, qa, prod etc. for example db properties. Like application-dev.properties etc.

@Profile(“qa”) on the method where we use the properties, also in the


application.properties file specify spring.profiles.active=qa

31. @Scope

@Scope annotations can only be used on the concrete bean class (for annotated
components) or the factory method (for @Bean methods). When used on the
concrete bean class as a type-level annotation together with @Component,
@Scope indicates the name of a scope to use for instances of the annotated type.
When used on the factory method as a method-level annotation together with
@Bean, @Scope indicates the name of a scope to use for the instance returned
from the method.

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 9/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

Scopes à singleton, prototype, request, session, globalSession

@Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

public ResourceBean getResourceBean () {

return new ResourceBean();

32. @Import

scoped bean injection problem - Injecting prototype bean into singleton bean,
both the beans will be initialized only once, the prototype bean will lose its
prototype behavior.

Use @Import (ProtoypeBean.class) at class level to fix this

33. @Loopup

Use annotation @Loopup at method level for injection, to solver the scoped bean
injection problem,

@Lookup

public ProtoypeBean getProtoypeBean () { return null; }

34. @Repository

Any Class that is annotated with @Repository annotation, plays a role as


repository or Data Access Object, spring creates a bean for the class and handles
exceptions properly.

It helps translate/converts the specific exceptions thrown by specific JPA


implementors into Spring’s DataAccessException hierarchy.

35. @NoRepositoryBean

This annotation is used to provide an extended base interface to all repositories.


Along with this base repository, a base class implementing the methods declared

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 10/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

in the base repository interface should be provided. When we extend our


repository from this base repository but do not want spring beans/repository
proxies for interface to be created we use @NoRepositoryBean, it means the
repository just serves as the base repository but no beans are created.

@NoRepositoryBean

public interface CustomBaseRepository<T, ID extends Serializable> extends


JpaRepository<T, ID> {

List<T> customMethodForAllRepositories(String attr1, String attr2);

public interface ExtendedUsertRepository extends CustomBaseRepository


<UserEntity, Long> {

36. @Entity

By annotating a class with @Entity, we are specifying that the class is correspond
to a particular DB table and DB operations can be performed on that class.

37. @Table

This annotation allows us to specify the table that a particular entity corresponds
to and that can be used to persist the entity in the database.

@Entity

@Table(name = "EMPLOYEE")

public class Employee {

@Id

@GeneratedValue

@Column(name = "id")

private int id;

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 11/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

This annotation is not mandatory, by default, entity class name is treated as the
name of the table, we can specify a different table name using this annotation.

38. @Id

This annotation is used to define the primary key of an entity.

Composite Primary key:

Using @IdClass or @EmbeddedId annotations

39. @IdClass

--

Public class PersonId impliments serializable{

Private String passportNumber;

Private String visaType;

@Entity

@IdClass(PersonId.class)

Public class Person{

@Id private String passportNumber;

@Id private String visaType;

40. @EmbeddedId

@EmbeddableClass

Class ReportId impliments serializable {

Int assessmentYear;
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 12/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

String quarter;

Class Report {

@EmbeddedId

ReportId reportId;

41. @GeneratedValue

This annotation is used to specify the primary key generation strategy,


GenerationType has 4 enum types, default is AUTO.

i. GenerationType. AUTO - persistence provider should automatically pick


an appropriate strategy for the particular database

ii. GenerationType. IDENTITY - primary keys for the entity using a database
identity column. IDENTITY, SQL server, MYSQL support this and some dbs does not
support.

iii. GenerationType.SEQUENCE – persistence provider uses database


sequence to provide id

iv. GenerationType.TABLE – must use a db table to provide or keep the next


id

42. @Column

This annotation denotes a column in table.

43. @OneToOne

This annotation is used to denote single entity is mapped to another single entity.
For example, Person and PassportDetails

@Entity

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 13/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

Public class Person{

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name="id")

private int id;

@Column(name="name")

private String name;

@OneToOne(cascade=CascadeType.ALL)

@JoinColumn(name="passport_number")

private PassportDetails passportDetails;

@Entity

@Table(name="passport_details")

public class PassportDetails {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name="passport_number")

private int passportNumber;

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 14/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

@OneToOne(mappedBy="passportDetails", cascade=
{CascadeType.REFRESH,CascadeType.DETACH,

CascadeType.PERSIST})

private Perosn person;

Cascade Types:

When we perform some operation like delete on one target entity, the same
action will be applied to associated entities

ALL - propagate all actions from parent to child entities

PERSIST - Propagates persist operation from parent to child

MERGE

REMOVE - Similar to hibernate CascadeType.DELETE

REFRESH

DETACH - removes from persistent context,

Hibernate Specific:

LOCK - Re-attaches parent entity and its child entities to persistent context.

REPLICATE

SAVE_UPDATE

44. @OneToMany and @ManyToOne

For example one department have many employees, the mapping can be specified
as follows:

@Entity

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 15/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

Public class Department{

@Id

@Column(name=”department_id”)

Private long department_id;

@OneToMany(fetch=FetchType.LAZY,mappedBy="department_id", cascade=
{CascadeType.PERSIST,CascadeType.MERGE,

CascadeType.DETACH,CascadeType.REFRESH})

private List<Employee> employees;

@Entity

Public class Employee{

@Id

@Column(name=”employee_id”)

Private long employee_id;

@ManyToOne( cascade= {CascadeType.PERSIST,CascadeType.MERGE,

CascadeType.DETACH,CascadeType.REFRESH})

@JoinColumn(name="department_id" )

private Department department;

The above relationship is bidirectional. If we want to specify a unidirectional


relationship, for example relationship between Product and Review entities, the

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 16/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

mapping entry need not be added in the Review entity

@Entity

Public class Product{

@Id

@Column(name=”product_id”)

Private long product_id;

@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)

@JoinColumn(name="product_id")

private List<Review> reviews;

@Entity

@Table(name="review")

public class Review {

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

private int id;

@Column(name="comment")

private String comment;

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 17/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

45. @ManyToMany

For example, multiple Students can enrol for multiple courses

@Entity

Public class Course{

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

Private int coursed;

@ManyToMany(fetch=FetchType.LAZY, cascade=
{CascadeType.PERSIST,CascadeType.MERGE,

CascadeType.DETACH,CascadeType.REFRESH})

@JoinTable(name="course_student",

joinColumns=@JoinColumn(name="course_id",
referencedColumnName="id"),

inverseJoinColumns=@JoinColumn(name="student_id",
referencedColumnName="id")

private List<Student> students;

@Entity

@Table(name="student")

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 18/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

public class Student implements Serializable{

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name="id")

private int id;

@ManyToMany(fetch=FetchType.LAZY, cascade=
{CascadeType.PERSIST,CascadeType.MERGE,

CascadeType.DETACH,CascadeType.REFRESH})

@JoinTable(name="course_student",

joinColumns=@JoinColumn(name="student_id",
referencedColumnName="id"),

inverseJoinColumns=@JoinColumn(name="course_id",
referencedColumnName="id")

private List<Course> courses;

46. @Query annotation

This annotation is used to execute queries for spring repository methods. It can
take JPQL or native SQL queries, by default it takes JPQL query.

@Query("SELECT o FROM Orders o WHERE o.status = ‘PENDING")


Collection<User> findAllPendingOrders();

To execute native sql, nativeQuery=true attribute should be passed

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 19/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

@Query( value = "SELECT * FROM Orders o WHERE o.status = ‘PENDING’",


nativeQuery = true)

Collection<User> findAllPendingOrdersNative();

47. @NamedQuery

This will help define the queries on one place, in the entity class and use them in
the repository class, this is a static query that gets evaluated at the time of
session factory creation

For example,

@Entity

@Table

@NamedQuery(name = "Order.findByStatus",

query = "select o from Order e where o.status = ?1")

public class Order { }

In the repository add the metod:

@Repository

public interface OrderRepository extends CrudRepository<Order, Integer> {

public List<Order> findByStatus(String status);

It can take other attributes like timeout, fetchsize, chacheable etc.,

48. @NamedNativeQuery

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 20/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

It uses native sql query, it is similar to @NamedQuery with some additional


configuration required. Also it can be used to make stored procedure and function
calls.

@org.hibernate.annotations.NamedNativeQueries(
@org.hibernate.annotations.NamedNativeQuery(name = "Order.findByOrderId",
query = "select * from Orders emp where order_id=:orderId", resultClass =
Order.class) )

In order to use the named native query, we need to do the following:

NativeQuery query = session.getNamedNativeQuery("Order.findByOrderId ");


query.setParameter("order_id", "12345");

Order result = (Order) query.getSingleResult();

49. @Modifying

This annotation is used along with the @Query annotation to execute commands
(CUD) operations

JPQL

@Modifying

@Query("update Order o set o.status = :status where orderId = :orderId")

Order updateOrderStatus( @Param("status ") String status, Param("orderId")


Integer orderId);

Native SQL

@Modifying

@Query(value = "update Order o set o.status = ? where o.order_id = ?",


nativeQuery = true)

Order updateOrderStatus (String status, Integer orderId);

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 21/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

50. @Version

This annotation is used for optimistic locking, to prevent lost updates, when
multiple transactions are reading/writing a particular entity. To implement this,
we need to add a property in the entity class

@Version

Private long version;

Using last modified date for versioning, as per documentation this is less reliable
than version number. DB is the default version, if we use VM, it uses timestamp of
virtual machine

@Version

@Source(value=SourceType.DB)

Private Date version;

When a particular entity is read, along with the entity version is also returned, and
when that particular entity is updated, version is incremented. Other transactions
that try to update the entity with older version will throw
OptimisticLockException, they need to read the latest version and try the update
operation.

This can also be used on the getter method.

@Version

Public long getVersion { return version}

51. @OptimisticLock

This annotation can be used with @Version, when we use @Version, the version
gets updated for any property change in the entity, if we want to exclude any
property from version update, we should use this annotation

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 22/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

@Column(name=”xyz”)

@OptimisticLock(excluded=true)

Private String xyz;

52. @OptimisticLocking

This annotation is used for versionless optimistic locking, it does not require
version attribute, this is useful with legacy schemas, version checks are performed
either with all the entity attributes or just attributes changed, it has a single
attribute of type OptimisticLockType. There are 4 Optimistic lock types

a. NONE – optimistic locking is disabled even if there is a @Version present

b. VERSION - Performs optimistic locking based on a @Version

c. ALL – All entity properties are used to verify the version of the entity

d. DIRTY – Only current dirty properties are used to verify entity version

@Entity(name = "product")

@Table(name = "product")

@OptimisticLocking(type = OptimisticLockType.DIRTY)

@DynamicUpdate

public class Product {

53. @DynamicUpdate

It takes value true or false, if true, dynamic sql will be generated with the changed
columns only as part of the prepared sql statement executed for update.

54. @Lock

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 23/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

This annotation is used to acquire the lock on a particular entity, we need to


annotate the target query method with this annotation

@Lock(LockModeType.PESSIMISTIC_READ)

public Optional<Customer> findById(Long customerId);

There are the following lock types

PESSIMISTIC_READ- prevents dirty reads

PESSIMISTIC_WRITE – it will prevent other transactions from read, write or delete


data, it needs to be acquired for any write operations.

PESSIMISTIC_FORCE_INCREMENT - this is similar to the PESSIMISTIC_WRITE but


also supports the versioning, for versioned entities it increments the version also.

55. @ EnableTransactionManagement

we can use in a class annotated with @Configuration to enable transactional


support.

@Configuration

@EnableTransactionManagement

public class JPATransactionConfig{

56. @Transactional

This annotation can be applied to method or class to indicate that the annotated
method or all methods in the annotated class should be executed within the
transaction.

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 24/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

This annotation supports configuration like:

propagation

REQUIRED, REQUIRES_NEW,MANDATORY,NEVER,SUPPORTS,NOT_SUPPORTED,
NESTED

isolation – enum - DEFAULT, READ_UNCOMMITTED, READ_COMMITTED,


REPEATABLE_READ, SERIALIZABLE

timeout

readonly

This is suitable for DTOs and VOs

noRollbackFor

noRollbackForClassName

57. @PersistenceContext

Persistence context manages entity life cycle in an application, EntityManager


instance is associated with persistence context, Entity manager is used to create,
or remove or find entities

There are two types of persistence contexts

a. Transaction Scoped Persistence Context:

It is bound to a transaction, as soon as transaction finishes, the entities are flushed


to persistent storage, this is default persistent context.

@PersistenceContext

private EntityManager entityManager;

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 25/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

b. Extended scoped persistent context

This spans multiple transactions

@PersistenceContext(type = PersistenceContextType.EXTENDED)

private EntityManager entityManager;

To view or add a comment, sign in

Insights from the community

Object-Relational Mapping (ORM)

What are some best practices for designing ORM models that are adaptable to future schema
changes?

Data Engineering

How can you use Apache Flink to extract data from cloud-based summarization tools?

Database Design

How do you validate and query json data efficiently and securely?

Database Development

What are the best practices for handling large datasets in ORM code?

Database Development

What is lazy loading in ORM and how does it impact performance in Database Development?

Process Automation

How can you optimize ETL performance with Python and Pandas?

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 26/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

Show more

Others also viewed

Complex nested JSON Transformation using Spark — RDD


Saikrishna Pujari · 4y

Spring Data JPA


Mihai Munteanu · 3mo

SOP article in CodeProject


Gerardo R. · 2mo

About DB Transaction and Spring @Transactional


Sameh Muhammed · 2y

Open-source data transformation with DataSonnet


Abhilash Nair · 2y

Introduction to Spring Data JPA


Omar Ismail · 2y

Show more

Explore topics
Sales

Marketing

Business Administration

HR Management

Content Management

Engineering

Soft Skills

See All

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 27/28
14/04/2024, 19:33 Springboot Annotations Quick Reference

© 2024 About

Accessibility User Agreement

Privacy Policy Cookie Policy

Copyright Policy Brand Policy

Guest Controls Community Guidelines

Language

https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 28/28

You might also like