Common Spring Boot and Hibernate Annotations

Zeeshan Shaikh
7 min readMar 21, 2021
  1. Core Spring Framework Annotations:
  • @Required: It applies to the bean setter method. It indicates that the annotated bean must be populated at configuration time with the required property, else it throws an exception BeanInitilizationException.
  • @Autowired: Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to auto-wire spring bean on setter methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-wires the bean by matching the data-type.
  • @Configuration: It is a class-level annotation. The class annotated with @Configuration used by Spring Containers as a source of bean definitions.
  • @ComponentScan: It is used when we want to scan a package for beans. It is used with the annotation
  • @Configuration. We can also specify the base packages to scan for Spring Components
  • @Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a bean to be managed by the Spring Container.

2. Spring Framework Stereotype Annotations:

  • @Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java class annotated with @Component is found during the classpath. The Spring Framework pick it up and configure it in the application context as a Spring Bean.
  • @Controller: The @Controller is a class-level annotation. It is a specialization of @Component. It marks a class as a web request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with @RequestMapping annotation.
  • @Service: It is also used at the class level. It tells the Spring that class contains business logic.
  • @Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the database directly. The repository does all the operations related to the database.

3. Spring Boot Annotations:

  • @SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration.
  • @EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. @SpringBootApplication.
  • @SpringBootTest: annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.
  • @Mock: creates mocks
  • @InjectMocks: creates objects and inject mocked dependencies

4. Spring MVC and REST Annotations:

  • @RequestMapping: It is used to map web requests. It has many optional elements like consumes, header, method, name, params, path, produces, and value. We use it with the class as well as the method.
  • @GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web service endpoint that fetches It is used instead of using: @RequestMapping(method = RequestMethod.GET)
  • @PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web service endpoint that creates It is used instead of using: @RequestMapping(method = RequestMethod.POST)
  • @PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web service endpoint that creates or updates It is used instead of using: @RequestMapping(method = RequestMethod.PUT)
  • @DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to create a web service endpoint that deletes a resource. It is used instead of using: @RequestMapping(method = RequestMethod.DELETE)
  • @PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is used instead of using: @RequestMapping(method = RequestMethod.PATCH)
  • @RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it uses HTTP MessageConverters to convert the body of the request. When we annotate a method parameter with @RequestBody, the Spring framework binds the incoming HTTP request body to that parameter.
  • @ResponseBody: It binds the method return value to the response body. It tells the Spring Boot Framework to serialize a return an object into JSON and XML format.
  • @PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web service, where the URL contains a path variable. We can define multiple @PathVariable in a method.
  • @RequestParam: It is used to extract the query parameters from the URL. It is also known as a query parameter. It is most suitable for web applications. It can specify default values if the query parameter is not present in the URL.
  • @RequestHeader: It is used to get the details about the HTTP request headers. We use this annotation as a method parameter. The optional elements of the annotation are name, required, value, defaultValue. For each detail in the header, we should specify separate annotations. We can use it multiple time in a method
  • @RestController: It can be considered as a combination of @Controller and @ResponseBody annotations. The @RestController annotation is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody.
  • @RequestAttribute: It binds a method parameter to request attribute. It provides convenient access to the request attributes from a controller method. With the help of @RequestAttribute annotation, we can access objects that are populated on the server-side.
  • @Value: Field level annotation used for injecting values into fields in Spring-managed beans. can be used to get application .properties values from file to java class
  • @ResponseEntity: Represents the whole HTTP response: status code, headers, and body.
  • @Qualifier: annotation is used to resolve the auto wiring conflict when there are multiple beans of the same type. The @Qualifier annotation can be used on any class annotated with @Component or on the method annotated with @Bean

5. spring-security annotations:

  • @EnableWebSecurity: The @EnableWebSecurity is a marker annotation. It allows Spring to find (it’s a @Configuration and, therefore, @Component) and automatically apply the class to the global WebSecurity.
  • @Secured: annotation can be used with multiple Roles and Authorities. For example, if you want a method to be invoked by users who are assigned either ROLE_ADMIN or SUPERADMIN, you can provide both authorities in the curly brackets.
  • @PreAuthorize: can check for authorization before entering into the method. The @PreAuthorize authorizes on the basis of role or the argument which is passed to the method.
  • @PostAuthorize: checks for authorisation after method execution. The @PostAuthorize authorizes on the basis of logged in roles, return an object by the method and passed the argument to the method.
  • @EnableGlobalMethodSecurity: Enables Spring Security global method security similar to the XML support.

6. Hibernate annotations:

All the JPA annotations are defined in the javax.persistence package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification.

  • @Transactional: Both queries should be updated otherwise rollback. ACID- Atomicity, Consistency, Isolation, Durability

Hibernate JPA annotations:

  • @Entity- Defines that a class can be mapped to a database table
  • @Table- Create a table
  • @Column-Create a column within the table
  • @Id-Specify the primary key of an entity
  • @GeneratedValue- This allows you to generate the primary key values. Choose a generation strategy from Auto (default), Identity, Sequence and Table
  • @SequenceGenerator- Defines a sequence when using the Sequence strategy as ID generation strategy
  • @Version- is used to implement Optimistic locking with Hibernate, which means that no two transactions override the data at the same time with a conflict.
  • @OrderBy- Order the contents by specific parameter
  • @Transient-Transient annotation in JPA or Hibernate is used to indicate that a field is not to be persisted or ignore fields to save in the database.

Hibernate Association Mapping Annotations (Most of them are self-explanatory):

  • @OneToOne- The @OneToOne annotation is used to create the one-to-one relationship between two entities
  • @ManyToOne- The @ManyToOne annotation is used to create the many-to-one relationship between entities
  • @OneToMany- The @OneToMany annotation is used to create the one-to-many relationship between entities
  • @ManyToMany- The @ManyToMany annotation is used to create the many-to-many relationship between entities
  • @PrimaryKeyJoinColumn- Specifies a primary key column that is used as a foreign key to join to another table.
  • @JoinColumn- Join two columns
  • @JoinTable- Join tables
  • @MapsId -in hibernate annotation maps a column with another table’s column. It can be used also to share the same primary key between 2 tables

Hibernate Inheritance Mapping Annotations:

  • @Inheritance-It is used to define the type of inheritance used in hibernate and it is defined in the parent class. If the Inheritance annotation is not specified or if no inheritance type is specified for an entity class hierarchy, the SINGLE_TABLE mapping strategy is used
  • @DiscriminatorColumn-Specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.
  • @DiscriminatorValue-Specifies the value of the discriminator column for entities of the given type.

Other annotations:

  • @LoadBalanced: for client-side load balancing
  • @FeignClient: feign is an HTTP client to send requests and receive a response from remote microservices. it is Declarative and load balanced.
  • @EnableFeignClients: Add @EnableFeignClients in the main class of spring boot
  • @Profile: allow developers to register beans by the condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load database properties file based on the application running in development, test, staging or production environment.
  • @CrossOrigin: annotation enables cross-origin resource sharing only for this specific method. By default, it allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used.

--

--

Zeeshan Shaikh

Software Developer with 6+ years of experience in Java and web technologies. Health and Fitness enthusiast.