Spring Data JPA

🚀 Common Spring Data JPA Annotations

  • @Entity → Marks a class as a JPA entity (maps to a table).
  • @Table → Specifies the table name in the database.
  • @Id → Marks a field as the primary key.
  • @GeneratedValue → Defines how the primary key is generated (IDENTITY, SEQUENCE, etc.).
  • @Column → Customizes column mapping (name, nullable, length, unique, etc.).
  • @ManyToOne / @OneToMany / @ManyToMany / @OneToOne → Relationship mappings.
  • @JoinColumn → Specifies the foreign key column.
  • @Repository → Marks a DAO interface (usually JpaRepository).
  • @EnableJpaRepositories → Enables JPA repositories (usually auto-configured in Spring Boot).
  • @Transactional → Declares transaction boundaries.

âš¡ Example: Spring Boot + PostgreSQL + Data JPA

1. Dependencies (pom.xml)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. Database Config (application.yml)

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: postgres
    password: mypassword
    driver-class-name: org.postgresql.Driver
  jpa:
    hibernate:
      ddl-auto: update   # create, create-drop, validate, update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

3. Entity Example (User.java)

import jakarta.persistence.*;

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

    @Column(nullable = false, length = 100)
    private String name;

    @Column(unique = true, nullable = false)
    private String email;

    // getters and setters
}

4. Repository (UserRepository.java)

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}

5. Service Layer (UserService.java)

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepository;
    
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

6. REST Controller (UserController.java)

import org.springframework.web.bind.annotation.*;
import java.util.List;

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

    private final UserService userService;
    
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @GetMapping
    public List<User> getUsers() {
        return userService.getAllUsers();
    }
}

✅ Now you can run your Spring Boot app, and interact with PostgreSQL via REST endpoints:

  • POST /api/users → create a new user
  • GET /api/users → list all users

Leave a Reply