0

[Java Backend Zero to Hello] Resources - Cheatsheet Tra Cứu Nhanh Backend Java

Java Backend Zero to Hello

📚 Bài viết thuộc series Java Backend Zero to Hello 📌 Phần: Tài Nguyên & Tham Khảo | Bài 85/86


CHEATSHEET - BACKEND JAVA

1. JAVA CORE

Primitive Types

byte, short, int, long, float, double, char, boolean

Collections

List<String> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<String, Integer> map = new HashMap<>();

Stream API

list.stream()
    .filter(x -> x > 0)
    .map(String::valueOf)
    .collect(Collectors.toList());

Optional

Optional<String> opt = Optional.ofNullable(value);
String result = opt.orElse("default");

Lambda

Runnable r = () -> System.out.println("Hello");
Function<Integer, Integer> square = x -> x * x;

2. SPRING BOOT

Main Annotations

@SpringBootApplication
@RestController
@RequestMapping("/api")
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping
@RequestBody, @PathVariable, @RequestParam
@Service, @Repository, @Component
@Autowired
@Configuration, @Bean

Dependency Injection

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository repository;
}

REST Controller

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public ResponseEntity<User> getById(@PathVariable Long id) {
        return ResponseEntity.ok(userService.findById(id));
    }

    @PostMapping
    public ResponseEntity<User> create(@RequestBody @Valid User user) {
        return ResponseEntity.status(HttpStatus.CREATED)
            .body(userService.create(user));
    }
}

Exception Handling

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorResponse(404, ex.getMessage()));
    }
}

3. SPRING DATA JPA

Entity

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;
}

Repository

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
    List<User> findByNameContaining(String name);
    Page<User> findByAge(int age, Pageable pageable);

    @Query("SELECT u FROM User u WHERE u.email = :email")
    Optional<User> findByEmailCustom(@Param("email") String email);
}

Relationships

@OneToOne, @OneToMany, @ManyToOne, @ManyToMany
@JoinColumn(name = "user_id")
mappedBy = "user"
fetch = FetchType.LAZY
cascade = CascadeType.ALL

4. SPRING SECURITY + JWT

Security Config

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**").permitAll()
                .anyRequest().authenticated()
            )
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            );
        return http.build();
    }
}

JWT

// Generate
String token = Jwts.builder()
    .subject(username)
    .expiration(new Date(System.currentTimeMillis() + 86400000))
    .signWith(key)
    .compact();

// Parse
Claims claims = Jwts.parser()
    .verifyWith(key)
    .build()
    .parseSignedClaims(token)
    .getPayload();

5. SQL

CRUD

SELECT * FROM users WHERE age > 18;
INSERT INTO users (name, email) VALUES ('An', 'an@example.com');
UPDATE users SET name = 'Bình' WHERE id = 1;
DELETE FROM users WHERE id = 1;

JOIN

SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.total > 100;

Aggregate

SELECT department, COUNT(*), AVG(salary)
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

6. MAVEN

Commands

mvn clean           # Xóa target/
mvn compile         # Compile
mvn test            # Test
mvn package         # Tạo JAR
mvn install         # Cài vào local repo
mvn spring-boot:run # Chạy app

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

7. GIT

Commands

git init
git add .
git commit -m "message"
git push origin main
git pull
git branch feature/x
git checkout feature/x
git merge main
git rebase main

8. DOCKER

Commands

docker build -t myapp:1.0 .
docker run -p 8080:8080 myapp:1.0
docker ps
docker stop <id>
docker-compose up -d
docker-compose down

Dockerfile

FROM eclipse-temurin:17-jre-jammy
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]

9. HTTP STATUS CODES

Code Ý nghĩa
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
500 Internal Server Error

10. DESIGN PATTERNS

Pattern Mục đích
Singleton 1 instance duy nhất
Factory Tạo object linh hoạt
Builder Xây dựng object phức tạp
Strategy Thuật toán thay đổi linh hoạt
Observer Thông báo sự kiện
Repository Tách data access
Decorator Thêm hành vi
Facade Đơn giản hóa hệ thống

11. SOLID

Nguyên lý Mô tả
SRP Single Responsibility
OCP Open/Closed
LSP Liskov Substitution
ISP Interface Segregation
DIP Dependency Inversion

🧭 Điều Hướng Series

⬅️ Bài trước: Phase 8 - Đặc Tả Kỹ Thuật Dự Án E-Commerce Backend

📋 Lộ trình tổng quan: Xem Toàn Bộ Series

➡️ Bài tiếp theo: Resources - Tài Liệu & Lộ Trình Tham Khảo


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí