The use of Spring Data annotations in Spring Boot

Sring Data JPA provides many useful annotations for us to implement a variety of complex functions. In this article, we will explain Spring Data Annotations and Spring Data JPA Annotations.

Spring Data Annotations

Annotations Spring Data Annotations refer to Annotations from the Spring-data-Commons package. Spring Data is not only available for JPA, it has many other Data providers, of which JPA is just one concrete implementation.

@Transactional

It is easy to configure a method to be Transactional using @Transactional:

@Transactional
void pay(a) {}
Copy the code

@Transactional can be placed ona method or ona class. Placing it ona class means that all methods in that class are available for Transactional.

@NoRepositoryBean

Sometimes when creating a parent Repository, we don’t need to create an implementation for the parent Repository, we just want to provide a common method for the child Repository. In this case, we can add the @noRepositoryBean annotation to the parent class:

@NoRepositoryBean
public interface ParentRepository<T.ID extends Serializable> extends CrudRepository<T.ID> {

    Optional<T> findById(ID id);
}
Copy the code

The subclasses are as follows:

@Repository
public interface ChildRepository extends ParentRepository<Person.Long> {}Copy the code

@Param

We can pass arguments in the Query statement by using @param:

@Query("FROM Person p WHERE p.name = :name")
Person findByName(@Param("name") String name);
Copy the code

@Id

@id indicates the primary key of the Entity:

class Person {
 
    @Id
    Long id;
 
    // ...
     
}
Copy the code

@Transient

By using @TRANSIENT, indicate that a field of Entity does not need to be stored.

class Person {
 
    // ...
 
    @Transient
    int age;
 
    // ...
 
}
Copy the code

@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate

From these notes, we can get the figures from the Principals:

public class Person {
 
    // ...
 
    @CreatedBy
    User creator;
     
    @LastModifiedBy
    User modifier;
     
    @CreatedDate
    Date createdAt;
     
    @LastModifiedDate
    Date modifiedAt;
 
    // ...
 
}
Copy the code

All these notes are used in conjunction with Spring Security because of the need to use the Principals.

Spring Data JPA Annotations

Annotations Spring Data JPA Annotations come from the Spring-Data-JPA package.

@Query

By using @query, we can customize SQL statements:

@Query("SELECT COUNT(*) FROM Person p")
long getPersonCount(a);
Copy the code

We can also pass arguments:

@Query("FROM Person p WHERE p.name = :name")
Person findByName(@Param("name") String name);
Copy the code

We can also use native SQL queries:

@Query(value = "SELECT AVG(p.age) FROM person p", nativeQuery = true)
int getAverageAge(a);
Copy the code

@Procedure

With @PROCEDURE, we can call stored procedures in the database:

@NamedStoredProcedureQueries({ 
    @NamedStoredProcedureQuery(
        name = "count_by_name", 
        procedureName = "person.count_by_name", 
        parameters = { 
            @StoredProcedureParameter(
                mode = ParameterMode.IN, 
                name = "name", 
                type = String.class),
            @StoredProcedureParameter(
                mode = ParameterMode.OUT, 
                name = "count", 
                type = Long.class) 
            }
    ) 
})
 
class Person {}
Copy the code

We can add this annotation to the Entity. Then see how to call:

@Procedure(name = "count_by_name")
long getCountByName(@Param("name") String name);
Copy the code

@Lock

By using @lock, we can choose how to isolate the database:

@Lock(LockModeType.NONE)
@Query("SELECT COUNT(*) FROM Person p")
long getPersonCount(a);
Copy the code

The value of Lock can be the following:

  • READ
  • WRITE
  • OPTIMISTIC
  • OPTIMISTIC_FORCE_INCREMENT
  • PESSIMISTIC_READ
  • PESSIMISTIC_WRITE
  • PESSIMISTIC_FORCE_INCREMENT
  • NONE

@Modifying

@modifying indicates that we have operations to modify the database:

@Modifying
@Query("UPDATE Person p SET p.name = :name WHERE p.id = :id")
void changeName(@Param("id") long id, @Param("name") String name);
Copy the code

@EnableJpaRepositories

To configure Japa Repository, use @EnableJpaRepositories:

@Configuration
@EnableJpaRepositories(basePackages = "com.flydean.repository")
public class PersistenceConfig {}Copy the code

By default, we will find repositories in a subclass of the @Configuration class. By using basePackages, we can specify additional directories.

Examples of this article can be found at :github.com/ddean2009/l…

See flydean’s blog for more tutorials