@Annotations in Spring

Sungju Kim·2024년 8월 26일

Sparta_Coding_Camp_TIL

목록 보기
23/53

Useful Annotations in...

  • Lombok
  • JPA

Lombok

Lombok provides several annotations that help reduce boilerplate code in Java by automatically generating common methods like getters, setters, constructors, and more. Here are five useful Lombok annotations besides @Getter & @Setter:

1. @ToString

  • Purpose: Generates a toString() method that includes all non-static fields.
  • Example:
    @ToString
    public class User {
        private String name;
        private int age;
    }
  • Result: User(name=John, age=30)

2. @NoArgsConstructor

  • Purpose: Generates a no-argument constructor for the class.
  • Example:
    @NoArgsConstructor
    public class User {
        private String name;
        private int age;
    }
  • Result: public User() { }

3. @AllArgsConstructor

  • Purpose: Generates a constructor with one parameter for each field in the class.
  • Example:
    @AllArgsConstructor
    public class User {
        private String name;
        private int age;
    }
  • Result: public User(String name, int age) { this.name = name; this.age = age; }

JPA

1. @Entity and @Table

import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Column;
import jakarta.persistence.OneToMany;
import java.util.List;

@Entity
@Table(name = "users")
public class User {

    @Id // autogenerates id in the table
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username", nullable = false, length = 50)
    private String name;

    @OneToMany(mappedBy = "user")
    private List<Order> orders;

    // Getters and setters...
}
  • Explanation: @Entity marks User as a JPA entity. @Table specifies the table name in the database. @Column customizes the mapping of the name field.

2. @Id & @GeneratedValue

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
  • Explanation: @Id identifies id as the primary key. @GeneratedValue specifies that the ID should be generated automatically.

3.@RestController & @RequestMapping

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
@RequestMapping("/api/users")
public class UserController {
    // Controller methods...
}
  • Explanation: @RestController makes UserController a RESTful web service controller. This means it can handle HTTP requests (e.g., GET, POST) and return responses in formats like JSON or XML @RequestMapping maps all requests starting with /api/users to this controller.

4. @GetMapping

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
    // Fetch user by ID
}
  • Explanation: @GetMapping("/{id}") maps HTTP GET requests to this method. The @PathVariable extracts the id from the URL.

5. @PostMapping and @RequestBody

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@PostMapping
public User createUser(@RequestBody User user) {
    // Save the new user
}
  • Explanation: @PostMapping maps HTTP POST requests to create a new user. @RequestBody binds the request body (in JSON or XML) to the User object.

6. @Transactional

import org.springframework.transaction.annotation.Transactional;

@Transactional
public void deleteUser(Long id) {
    // Delete user by ID
}
  • Explanation: @Transactional ensures that this method runs within a transaction, so all database operations will either complete successfully or roll back if there's an error.

Summary

  • @Entity and @Table: Define database entities and their table mapping.
  • @Id, @GeneratedValue, @Column: Manage primary keys and column properties.
  • @RestController, @RequestMapping, @GetMapping, @PostMapping, @RequestBody, @PathVariable: Handle HTTP requests in REST controllers.
  • @Transactional: Manage database transactions.
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글