A Complete Guide to Spring Data Annotations (with Examples)

2 min read

A Complete Guide to Spring Data Annotations (with Examples)

Spring Data simplifies data access and repository implementation by eliminating boilerplate code. At the core of Spring Data JPA are a number of annotations that help define relationships, repository behavior, and entity mappings.

Below is a categorized list of essential Spring Data (JPA) annotations, each with a brief explanation and example.


1. @Entity

Marks a class as a JPA entity, which maps to a database table.

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    private Long id;
    private String name;
}

2. @Id

Marks a field as the primary key.

@Id
private Long id;

3. @GeneratedValue

Specifies how the primary key is generated (e.g., auto-increment).

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

4. @Table

Defines the table name if it differs from the entity name.

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

5. @Column

Customizes the column mapping.

@Column(name = "user_name", nullable = false)
private String name;

6. @Repository

Marks an interface as a Spring Data repository.

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

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

7. @Query

Defines custom JPQL or native SQL queries.

@Query("SELECT u FROM User u WHERE u.name = :name")
List<User> findByName(@Param("name") String name);

8. @Param

Used to bind method parameters to query parameters in @Query.

@Query("SELECT u FROM User u WHERE u.name = :name")
List<User> findByName(@Param("name") String name);

9. @Modifying

Used for update or delete queries.

@Modifying
@Query("UPDATE User u SET u.name = :name WHERE u.id = :id")
void updateNameById(@Param("id") Long id, @Param("name") String name);

Requires @Transactional on the method or class.


10. @Transactional

Marks a method or class to be transactional.

@Transactional
@Modifying
@Query("DELETE FROM User u WHERE u.name = :name")
void deleteByName(@Param("name") String name);

11. @EnableJpaRepositories

Enables JPA repositories in a Spring configuration class.

@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.repository")
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

12. @EntityListeners

Used for entity lifecycle callbacks (e.g., auditing).

@Entity
@EntityListeners(AuditingEntityListener.class)
public class AuditableUser {
    @CreatedDate
    private LocalDateTime createdDate;
}

13. @CreatedDate, @LastModifiedDate

Part of Spring Data Auditing to track creation and update times.

@CreatedDate
private LocalDateTime createdDate;

@LastModifiedDate
private LocalDateTime lastModifiedDate;

14. @MappedSuperclass

Defines a superclass whose fields are inherited by JPA entities.

@MappedSuperclass
public abstract class BaseEntity {
    @Id
    @GeneratedValue
    private Long id;
}

15. @Inheritance

Used for entity inheritance mapping.

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Animal {
    @Id
    private Long id;
}

@Entity
public class Dog extends Animal {
    private String breed;
}

16. @OneToOne, @OneToMany, @ManyToOne, @ManyToMany

Define relationships between entities.

// ManyToOne
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;

// OneToMany
@OneToMany(mappedBy = "department")
private List<Employee> employees;

17. @JoinColumn

Defines the foreign key column for relationships.

@JoinColumn(name = "dept_id")
private Department department;

18. @Cascade

While not part of JPA itself, in Hibernate-specific scenarios:

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Order> orders;

19. @NamedQuery

Defines named queries at the entity level.

@Entity
@NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")
public class User {
    // ...
}

Spring Boot Auto-Config

In Spring Boot, many things are auto-configured, so simply extending JpaRepository and annotating your application with @SpringBootApplication is often enough to get started.


Example: Putting It All Together

@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;
}

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByTitle(String title);
}

Summary

Spring Data JPA offers powerful abstractions that reduce the boilerplate in data access layers. Here’s a quick summary of what we covered:

AnnotationPurpose
@EntityDeclares a class as a JPA entity
@Id, @GeneratedValueMarks and generates primary key
@Table, @ColumnMaps entity to DB table/columns
@RepositoryMarks interface for repository
@Query, @ParamDefines custom queries
@Modifying, @TransactionalFor update/delete queries
@EnableJpaRepositoriesBootstraps JPA repositories
@CreatedDate, @LastModifiedDateAuditing fields
Relationship annotations@OneToOne, @ManyToOne, etc.

🤞 Never miss a story from us, get weekly updates to your inbox!

Leave a Reply

Your email address will not be published. Required fields are marked *