Hibernate in Spring Boot

🔑 Hibernate / JPA Annotations Cheat Sheet

AnnotationPurpose
@EntityMarks a class as a persistent entity (mapped to a table).
@Table(name = "...")Customizes the table name.
@IdMarks the primary key field.
@GeneratedValue(strategy = ...)Specifies primary key generation strategy. Common for Postgres: GenerationType.IDENTITY or GenerationType.SEQUENCE.
@ColumnCustomizes a column (name, nullable, length, unique, etc.).
@ManyToOneDefines a many-to-one relationship (foreign key).
@OneToManyDefines a one-to-many relationship (list/collection).
@JoinColumnSpecifies the foreign key column.
@OneToOneDefines one-to-one mapping.
@ManyToManyDefines many-to-many relationship (via join table).
@Enumerated(EnumType.STRING)Store enums as strings in DB.
@LobMaps large objects (text/blob).
@CreationTimestamp / @UpdateTimestampAuto-manage created/updated timestamps (Hibernate-specific).

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

1. Dependencies (pom.xml)

<dependencies>
    <!-- Spring Boot JPA (includes Hibernate) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- PostgreSQL Driver -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- Web for REST API -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. Configuration (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   # options: create, create-drop, update, validate
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        dialect: org.hibernate.dialect.PostgreSQLDialect

3. Entity with Relationships (User and Post)

import jakarta.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
import java.util.List;

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

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

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

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Post> posts;

    @CreationTimestamp
    private LocalDateTime createdAt;

    @UpdateTimestamp
    private LocalDateTime updatedAt;

    // getters & setters
}
import jakarta.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDateTime;

@Entity
@Table(name = "posts")
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Lob
    private String content;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

    @CreationTimestamp
    private LocalDateTime createdAt;

    // getters & setters
}

4. Repository Interfaces

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

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {
}

5. Service Layer

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

@Service
public class UserService {
    private final UserRepository userRepository;
    private final PostRepository postRepository;

    public UserService(UserRepository userRepository, PostRepository postRepository) {
        this.userRepository = userRepository;
        this.postRepository = postRepository;
    }

    @Transactional
    public User createUserWithPost(User user, Post post) {
        post.setUser(user);
        user.getPosts().add(post);
        return userRepository.save(user);
    }

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

6. REST Controller

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.createUserWithPost(user, user.getPosts().get(0));
    }

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

✅ Example Workflow

  • POST /api/users
{
  "name": "Alice",
  "email": "alice@example.com",
  "posts": [
    { "title": "My first post", "content": "Hello Hibernate + Postgres!" }
  ]
}
  • GET /api/users → returns users with posts.

Leave a Reply