0% found this document useful (0 votes)
9 views16 pages

Java Annotations

all about

Uploaded by

rakeshmishrare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

Java Annotations

all about

Uploaded by

rakeshmishrare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Spring Annotations

Annotation Name Summary, Syntax, and Examples


1. Core Spring
Annotations
- Summary:
Indicates a Spring-managed component (bean).

Syntax:
@Component
@Component
Examples:
java <br> @Component <br> public class MyService { <br> //
Business logic here <br> } <br>
Where to Use:
On classes that should be registered as beans in the Spring container.
- Summary:
A specialization of @Component, indicating that the annotated class is a
service.

Syntax:
@Service
@Service
Examples:
java <br> @Service <br> public class UserService { <br> // User-
related business logic <br> } <br>
Where to Use:
On service layer classes containing business logic.
- Summary:
A specialization of @Component, indicating that the class is a data access
object (DAO).

Syntax:
@Repository
@Repository
Examples:
java <br> @Repository <br> public interface UserRepository extends
JpaRepository<User, Long> { <br> } <br>
Where to Use:
On classes responsible for data access, typically extending JPA repositories.

@Controller - Summary:
A specialization of @Component, marking the class as a Spring MVC
controller.

Syntax:
@Controller

Examples:
java <br> @Controller <br> public class UserController { <br> //
Request handling methods <br> } <br>
Where to Use:
On classes that handle web requests in a Spring MVC application.
- Summary:
Combines @Controller and @ResponseBody, simplifying the creation of
RESTful web services.

Syntax:
@RestController
@RestController
Examples:
java <br> @RestController <br> public class UserRestController {
<br> // RESTful endpoints <br> } <br>
Where to Use:
On classes that expose RESTful web services, typically returning JSON or
XML.
2. Dependency Injection
Annotations
- Summary:
Automatically injects a dependency into a field, constructor, or setter
method.

Syntax:
@Autowired
@Autowired
Examples:
java <br> @Autowired <br> private UserService userService; <br>
Where to Use:
On fields, constructors, or methods where dependencies should be
injected by Spring.
- Summary:
Specifies the bean to be injected when there are multiple candidates.
@Qualifier
Syntax:
@Qualifier("beanName")
Examples:
java <br> @Autowired <br> @Qualifier("specificService") <br>
private MyService myService; <br>
Where to Use:
On dependency injections where you need to specify which bean to inject.
3. Spring MVC
Annotations
- Summary:
Maps HTTP requests to handler methods of MVC and REST controllers.

Syntax:
@RequestMapping("/path")
@RequestMapping
Examples:
java <br> @RequestMapping("/users") <br> public String listUsers()
{ <br> return "userList"; <br> } <br>
Where to Use:
On controller methods to define the URL paths they handle.
- Summary:
A shortcut for @RequestMapping with the HTTP GET method.

Syntax:
@GetMapping("/path")
@GetMapping
Examples:
java <br> @GetMapping("/users") <br> public List<User> getUsers()
{ <br> return userService.getAllUsers(); <br> } <br>
Where to Use:
On methods that handle HTTP GET requests.
- Summary:
A shortcut for @RequestMapping with the HTTP POST method.

Syntax:
@PostMapping("/path")
@PostMapping
Examples:
java <br> @PostMapping("/users") <br> public void
addUser(@RequestBody User user) { <br>
userService.saveUser(user); <br> } <br>
Where to Use:
On methods that handle HTTP POST requests.
@PutMapping - Summary:
A shortcut for @RequestMapping with the HTTP PUT method.

Syntax:
@PutMapping("/path")

Examples:
java <br> @PutMapping("/users/{id}") <br> public void
updateUser(@PathVariable Long id, @RequestBody User user) {
<br> userService.updateUser(id, user); <br> } <br>
Where to Use:
On methods that handle HTTP PUT requests.
- Summary:
A shortcut for @RequestMapping with the HTTP DELETE method.

Syntax:
@DeleteMapping("/path")
@DeleteMapping
Examples:
java <br> @DeleteMapping("/users/{id}") <br> public void
deleteUser(@PathVariable Long id) { <br>
userService.deleteUser(id); <br> } <br>
Where to Use:
On methods that handle HTTP DELETE requests.
4. Transaction
Management Annotations
- Summary:
Marks a method or class as transactional, automatically managing
transactions.

Syntax:
@Transactional
@Transactional
Examples:
java <br> @Transactional <br> public void transferMoney(Account
from, Account to, BigDecimal amount) { <br> // Transactional code
here <br> } <br>
Where to Use:
On service methods or classes where transactions should be managed
automatically.
5. Validation Annotations
- Summary:
@Valid Validates the annotated object before executing the method.
Syntax:
@Valid

Examples:
java <br> @PostMapping("/users") <br> public void
createUser(@Valid @RequestBody User user) { <br>
userService.saveUser(user); <br> } <br>
Where to Use:
On method parameters to enforce validation constraints on input objects.
- Summary:
Ensures that the annotated field is not null.

Syntax:
@NotNull
@NotNull
Examples:
java <br> public class User { <br> @NotNull <br> private String
name; <br> } <br>
Where to Use:
On fields in classes to enforce that they cannot be null.
- Summary:
Ensures that the annotated field has a minimum value.

Syntax:
@Min(value)
@Min
Examples:
java <br> public class Product { <br> @Min(1) <br> private int
quantity; <br> } <br>
Where to Use:
On numeric fields to enforce a minimum value constraint.
6. Exception Handling
Annotations
- Summary:
Defines a method to handle specific exceptions thrown by controller
methods.

@ExceptionHandler
Syntax:
@ExceptionHandler(Exception.class)

Examples:
java <br> @ExceptionHandler(UserNotFoundException.class) <br>
public ResponseEntity<String>
handleUserNotFound(UserNotFoundException ex) { <br> return new
ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
<br> } <br>
Where to Use:
On methods in controllers to handle exceptions.
- Summary:
Allows handling of exceptions across multiple controllers globally.

Syntax:
@ControllerAdvice

Examples:
@ControllerAdvice java <br> @ControllerAdvice <br> public class
GlobalExceptionHandler { <br> @ExceptionHandler(Exception.class)
<br> public ResponseEntity<String>
handleGlobalException(Exception ex) { <br> return new
ResponseEntity<>(ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR); <br> } <br> } <br>
Where to Use:
On classes that handle exceptions globally across all controllers.
JPA Annotations
Annotation Name Summary, Syntax, and Examples
- Summary:
Marks a class as a JPA entity, which maps to a
database table.

Syntax:
@Entity
@Entity
Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br> private
String name; <br> } <br>
Where to Use:
On classes that should be mapped to database
tables.
- Summary:
Specifies the table name for a JPA entity.

Syntax:
@Table(name = "table_name")

@Table Examples:
java <br> @Entity <br> @Table(name =
"users") <br> public class User { <br> @Id
<br> private Long id; <br> private String name;
<br> } <br>
Where to Use:
On entity classes when you need to customize the
table name.
- Summary:
Marks a field as the primary key of a JPA entity.

Syntax:
@Id

@Id Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br> private
String name; <br> } <br>
Where to Use:
On fields that represent the primary key of the
entity.
- Summary:
Specifies the generation strategy for the primary
key.

Syntax:
@GeneratedValue(strategy =
GenerationType.AUTO)
@GeneratedValue
Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> @GeneratedValue(strategy =
GenerationType.IDENTITY) <br> private Long
id; <br> } <br>
Where to Use:
On primary key fields to indicate how they should
be generated.
- Summary:
Maps a field to a specific column in a database
table.

Syntax:
@Column(name = "column_name")

@Column Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@Column(name = "email") <br> private String
emailAddress; <br> } <br>
Where to Use:
On fields where you need to customize the
database column mapping.
- Summary:
Defines a one-to-one relationship between two
entities.

Syntax:
@OneToOne
@OneToOne
Examples:
java <br> @Entity <br> public class
UserProfile { <br> @Id <br> private Long id;
<br> @OneToOne <br> @JoinColumn(name
= "user_id") <br> private User user; <br> }
<br>
Where to Use:
On fields that represent a one-to-one relationship
with another entity.
- Summary:
Defines a many-to-one relationship between two
entities.

Syntax:
@ManyToOne

@ManyToOne Examples:
java <br> @Entity <br> public class Order {
<br> @Id <br> private Long id; <br>
@ManyToOne <br> @JoinColumn(name =
"user_id") <br> private User user; <br> } <br>
Where to Use:
On fields that represent a many-to-one
relationship with another entity.
- Summary:
Defines a one-to-many relationship between two
entities.

Syntax:
@OneToMany(mappedBy = "field")

@OneToMany Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@OneToMany(mappedBy = "user") <br>
private List<Order> orders; <br> } <br>
Where to Use:
On fields that represent a one-to-many
relationship with another entity.
- Summary:
Defines a many-to-many relationship between two
entities.

Syntax:
@ManyToMany
@ManyToMany
Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@ManyToMany <br> @JoinTable(name =
"user_roles", <br> joinColumns =
@JoinColumn(name = "user_id"), <br>
inverseJoinColumns = @JoinColumn(name =
"role_id")) <br> private List<Role> roles; <br> }
<br>

Where to Use:
On fields that represent a many-to-many
relationship with another entity.
- Summary:
Specifies the foreign key column for an association.

Syntax:
@JoinColumn(name = "column_name")

@JoinColumn Examples:
java <br> @Entity <br> public class Order {
<br> @Id <br> private Long id; <br>
@ManyToOne <br> @JoinColumn(name =
"user_id") <br> private User user; <br> } <br>
Where to Use:
On fields that represent relationships, to customize
the foreign key column name.
- Summary:
Specifies the table used to map many-to-many
relationships.

Syntax:
@JoinTable(name = "table_name", <br>
joinColumns = @JoinColumn(name =
"column_name"), <br> inverseJoinColumns =
@JoinColumn(name =
"inverse_column_name"))

@JoinTable Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@ManyToMany <br> @JoinTable(name =
"user_roles", <br> joinColumns =
@JoinColumn(name = "user_id"), <br>
inverseJoinColumns = @JoinColumn(name =
"role_id")) <br> private List<Role> roles; <br> }
<br>
Where to Use:
On fields that represent many-to-many
relationships to specify the join table and columns.
- Summary:
@Inheritance
Specifies the inheritance strategy for JPA entities.
Syntax:
@Inheritance(strategy =
InheritanceType.SINGLE_TABLE)

Examples:
java <br> @Entity <br> @Inheritance(strategy
= InheritanceType.JOINED) <br> public class
Payment { <br> @Id <br> private Long id; <br>
} <br>
Where to Use:
On base entity classes to define how inheritance is
handled.
- Summary:
Specifies the column used to differentiate between
entity types in a single table inheritance strategy.

Syntax:
@DiscriminatorColumn(name =
"column_name", discriminatorType =
DiscriminatorType.STRING)
@DiscriminatorColumn
Examples:
java <br> @Entity <br> @Inheritance(strategy
= InheritanceType.SINGLE_TABLE) <br>
@DiscriminatorColumn(name =
"payment_type") <br> public class Payment {
<br> @Id <br> private Long id; <br> } <br>
Where to Use:
On base entity classes to define a discriminator
column in single table inheritance.
- Summary:
Indicates that the class is not an entity itself but its
properties are inherited by entities.

Syntax:
@MappedSuperclass
@MappedSuperclass
Examples:
java <br> @MappedSuperclass <br> public
abstract class Auditable { <br>
@Column(name = "created_date") <br>
private LocalDateTime createdDate; <br> //
Other common fields <br> } <br>
Where to Use:
On superclasses whose fields should be part of the
entities that inherit them.
- Summary:
Marks a class as embeddable, meaning its
properties are part of the entity that embeds it.

Syntax:
@Embeddable

Examples:
@Embeddable
java <br> @Embeddable <br> public class
Address { <br> private String street; <br>
private String city; <br> } <br> @Entity <br>
public class User { <br> @Id <br> private Long
id; <br> @Embedded <br> private Address
address; <br> } <br>
Where to Use:
On classes whose properties should be part of
another entity's table.
- Summary:
Embeds an embeddable class within an entity,
including its properties as columns in the entity's
table.

Syntax:
@Embedded
@Embedded
Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@Embedded <br> private Address address;
<br> } <br>
Where to Use:
On fields that are instances of embeddable classes.
- Summary:
Allows overriding of attributes in an embeddable
class when embedded in an entity.

Syntax:
@AttributeOverrides @AttributeOverrides({
@AttributeOverride(name = "propertyName",
column = @Column(name =
"new_column_name")) })

Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@Embedded <br> @AttributeOverrides({ <br>
@AttributeOverride(name = "street", column =
@Column(name = "home_street")), <br>
@AttributeOverride(name = "city", column =
@Column(name = "home_city")) <br> }) <br>
private Address homeAddress; <br> } <br>
Where to Use:
On fields where you want to customize the column
mappings of an embedded class.
- Summary:
Specifies a single attribute override for an
embedded class property.

Syntax:
@AttributeOverride(name = "propertyName",
column = @Column(name =
"new_column_name"))

@AttributeOverride Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@Embedded <br> @AttributeOverride(name =
"street", column = @Column(name =
"home_street")) <br> private Address
homeAddress; <br> } <br>
Where to Use:
On fields where you need to override the column
mapping for a single attribute of an embedded
class.
- Summary:
Marks a field as a large object (LOB) to be stored as
either a BLOB (Binary Large Object) or CLOB
(Character Large Object).

Syntax:
@Lob
@Lob
Examples:
java <br> @Entity <br> public class Document
{ <br> @Id <br> private Long id; <br> @Lob
<br> private byte[] content; <br> } <br>
Where to Use:
On fields that should be stored as large objects in
the database.
- Summary:
Specifies the temporal precision (date, time, or
timestamp) of a java.util.Date or
java.util.Calendar field.

Syntax:
@Temporal(TemporalType.TIMESTAMP)

@Temporal Examples:
java <br> @Entity <br> public class Event {
<br> @Id <br> private Long id; <br>
@Temporal(TemporalType.TIMESTAMP) <br>
private Date eventDate; <br> } <br>
Where to Use:
On fields of type java.util.Date or
java.util.Calendar to specify how they should be
stored in the database.
- Summary:
Specifies that a field should be persisted as an
enum, either as an ordinal or a string.

Syntax:
@Enumerated(EnumType.STRING)

@Enumerated Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@Enumerated(EnumType.STRING) <br>
private UserRole role; <br> } <br>
Where to Use:
On enum fields to specify how they should be
stored in the database (as a string or an ordinal).
- Summary:
Indicates that a field should not be persisted to the
database.

Syntax:
@Transient
@Transient

Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br>
@Transient <br> private int age; <br> } <br>
Where to Use:
On fields that should not be stored in the
database, such as computed properties or
temporary fields.
- Summary:
Defines a static, named query at the entity level.

Syntax:
@NamedQuery(name = "query_name", query
= "JPQL_query_string")

@NamedQuery Examples:
java <br> @Entity <br> @NamedQuery(name
= "User.findByName", query = "SELECT u
FROM User u WHERE u.name = :name") <br>
public class User { <br> @Id <br> private Long
id; <br> private String name; <br> } <br>
Where to Use:
On entity classes to define reusable, named JPQL
queries.
- Summary:
Groups multiple @NamedQuery annotations
together.

Syntax:
@NamedQueries({ @NamedQuery(name =
"query_name1", query =
"JPQL_query_string1"), @NamedQuery(name
= "query_name2", query =
"JPQL_query_string2") })
@NamedQueries
Examples:
java <br> @Entity <br> @NamedQueries({
<br> @NamedQuery(name =
"User.findByName", query = "SELECT u
FROM User u WHERE u.name = :name"),
<br> @NamedQuery(name = "User.findAll",
query = "SELECT u FROM User u") <br> })
<br> public class User { <br> @Id <br> private
Long id; <br> private String name; <br> } <br>
Where to Use:
On entity classes to define multiple named queries.
- Summary:
Indicates a version field used for optimistic locking.
@Version
Syntax:
@Version
Examples:
java <br> @Entity <br> public class User {
<br> @Id <br> private Long id; <br> @Version
<br> private int version; <br> } <br>
Where to Use:
On fields that should be used for optimistic locking
in the database.

You might also like