Spring Data Annotations

-

Introduction

Spring Data provides an abstraction over data storage technologies.


Common Spring Data Annotations

@Transactional

@NoRepositoryBean

@Param

1
2
@Query("FROM Person p WHERE p.name = :name")
Person findByName(@Param("name") String name);

@Id

@Id marks a field in a model class as the primary key

1
2
3
4
5
class Person {

@Id
Long id;
}

@Transient

We can use this annotation to mark a field in a model class as transient. Hence the data store engine won’t read or write this field’s value

1
2
3
4
5
class Person {

@Transient
int age;
}

@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate

With these annotations, we can audit our model classes: Spring automatically populates the annotated fields with the principal who created the object, last modified it, and the date of creation, and last modification:

Note, that if we want Spring to populate the principals, we need to use Spring Security as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Person {

@CreatedBy
User creator;

@LastModifiedBy
User modifier;

@CreatedDate
Date createdAt;

@LastModifiedDate
Date modifiedAt;

// ...

}

Spring Data JPA Annotations

@Query

@Procedure

@Lock

We can configure the lock mode when we execute a repository query method

  • READ
  • WRITE
  • OPTIMISTIC
  • OPTIMISTIC_FORCE_INCREMENT
  • PESSIMISTIC_READ
  • PESSIMISTIC_WRITE
  • PESSIMISTIC_FORCE_INCREMENT
  • NONE
1
2
3
@Lock(LockModeType.NONE)
@Query("SELECT COUNT(*) FROM Person p")
long getPersonCount();

@Modifying

1
2
3
@Modifying
@Query("UPDATE Person p SET p.name = :name WHERE p.id = :id")
void changeName(@Param("id") long id, @Param("name") String name);

@EnableJpaRepositories

1
2
3
@Configuration
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
class PersistenceJPAConfig {}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×