Web/spring

[Annotation] Spring Data Annotations

태애니 2023. 4. 1. 12:31
728x90

 

https://www.baeldung.com/spring-data-annotations

 

 

 


 

Spring Data provides an abstraction over data storage technologies.

Therefore, our business logic code can be much more independent of the underlying persistence implementation.

Also, Spring simplifies the handling of implementation-dependent details of data storage.

 

In this tutorial, we'll see the most common annotations of the Spring Data, Spring Data JPA, and Spring Data MongoDB projects.

 

@Transactional

method 의 transaction 동작을 구성할 경우 사용한다

클래스 수준에서 사용하면 클래스 내부 모든 메소드에서 작동하는데 또 특정 메소드에 적용하여 효과를 재정의할 수 있다

@Transactional
void pay() {}

https://www.baeldung.com/transaction-configuration-with-jpa-and-spring

 

 

 

@NoRepositoryBean

we want to create repository interfaces with the only goal of providing common methods for the child repositories.

@NoRepositoryBean 는 주입하지 않게한다.

org.springframework.data.repository.Repository 의 child 인터페이스를 표시할 때 Spring에게 bean을 생성하지 않도록 하게 한다

 

예시는 모든 리포지토리에서 Optional<T> findById(ID id)  메서드를 원하는 경우 기본 리포지토리를 만들게 한다

@NoRepositoryBean
interface MyUtilityRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
    Optional<T> findById(ID id);
}

 

이 애노테이션은 child interface에 영향을 주지 않는다.

@Repository
interface PersonRepository extends MyUtilityRepository<Person, Long> {}

이전 T findOne(ID id) 를 대체하는 이 메서드를 포함하는 Spring Data 버전 2 이후로 위의 예제는 필요없다

 

 

 

@Param

@Param을 사용하여 명명된 매개변수를 쿼리에 전달한다

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

https://www.baeldung.com/spring-data-jpa-query

 

 

 

 

@ID

Model class의 필드를 primary key로 표시

class Person {

    @Id
    Long id;

    // ...
    
}

Since it's implementation-independent, it makes a model class easy to use with multiple data store engines.

 

 

 

 

 

@Transient

모델 클래스의 필드를 일시적으로 표시한다. db engine은 이 값을 read, write 하지 않는다

class Person {

    // ...

    @Transient
    int age;

    // ...

}

@ID 하단 설명과 마찬가지로 구현 독립적이므로 여러 데이터 저장소 구현과 함께 사용하기 편하다

 

 

 

 

@CreatedBy , @LastModifiedBy , @CreatedDate , @LastModifiedDate

각각, 작성주체, 마지막수정주체, 작성날짜, 수정날짜 필드를 자동으로 채워주는 기능이다

public class Person {

    // ...

    @CreatedBy
    User creator;
    
    @LastModifiedBy
    User modifier;
    
    @CreatedDate
    Date createdAt;
    
    @LastModifiedDate
    Date modifiedAt;

    // ...

}

추가 적용해야할 것들이 있다

 

Security도 써야하고

Application 에도 @EnableJpaAuditing 을 써주는 등의 추가 작업이 필요하다 

@EnableJpaAuditing // Auditing을 사용
public class WebApplication {

   public static void main(String[] args) {
      SpringApplication.run(WebApplication.class, args);
   }


}

 

https://www.baeldung.com/database-auditing-jpa

여기를 참고

 

 

 


Spring Data JPA Annotations

 

 

 

@Query

With @Query, we can provide a JPQL implementation for a repository method:

나는 보통 제공해주는 함수를 많이 쓰는데

부득이하게 직접 쿼리를 짜야할 경우는 분명히 있을 것이다

그럴 때 쓴다

 

@Query("SELECT COUNT(*) FROM Person p")
long getPersonCount();

Also, we can use named parameters: 명명매개변수 사용

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

Besides, we can use native SQL queries, if we set the nativeQuery argument to true:

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

https://www.baeldung.com/spring-data-jpa-query

 

 

 

@Procedure

Spring Data JPA를 사용하면 리포지토리에서 저장 procedure를 쉽게 호출할 수 있다

 

먼저 표준 JPA 애노테이션을 사용하여 엔티티 클래스에서 저장소를 선언한다

@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 {}

 

이후 name 인수에서 선언한 이름으로 저장소 참조가 가능하다

 

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

 

 

 

@Lock

configure the lock mode when we execute a repository query method

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

The available lock modes:

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

 

@Modifying

 modify data with a repository method if we annotate it with @Modifying

업데이트할 때는 이 쿼리를 써주어야한다

 

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

 

 

@EnableJpaRepositories

To use JPA repositories, we have to indicate it to Spring. We can do this with @EnableJpaRepositories.

Note, that we have to use this annotation with @Configuration

 

JpaRepository 사용 시 선언해야한다.

@Configuration과 함께 사용할 것 <<<<<

@Configuration
@EnableJpaRepositories
class PersistenceJPAConfig {}

 

 

Spring은 @Configuration 클래스 하위 패키지에서 저장소를 찾는데,

basePackages 인수를 사용해 이를 변경 할 수 있다

@Configuration
@EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao")
class PersistenceJPAConfig {}

클래스 경로에서 Spring Data JPA를 찾으면 자동으로 이 작업을 수행한다

 

 

 


Spring Data Mongo Annotations

 

MongoDB는.. 사실 실무에서 지금 안쓰지만 그래도 한번 정리해보기로

 

Spring Data makes working with MongoDB much easier. In the next sections, we'll explore the most basic features of Spring Data MongoDB.Spring Data makes working with MongoDB much easier. In the next sections, we'll explore the most basic features of Spring Data MongoDB.

 

 

 

 

@Document

클래스를 db에 유지하는 도메인 개체로 표시

@Document
class User {}


// 컬렉션 이름 지정 가능
@Document(collection = "user")
class User {}


// @Document < 이 주석은 JPA @Entity 와 동등함

 

 

 

@Field

MongoDB 가 document를 유지할 때 사용할 필드 이름을 구성시킴

 

@Document
class User {

    // ...

    @Field("email")
    String emailAddress;

    // ...

}

// @Field 는 JPA의 @Column 에 해당

 

 

 

@Query

finder query 제공

@Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name);

 

 

 

@EnableMongoRepositories

Mongo Repository 를 사용하겠다고 선언해줌

@Configuration과 함께 사용할 것 <<< 

 

@Configuration
@EnableMongoRepositories
class MongoConfig {}

Spring은 이 @Configuration  클래스 의 하위 패키지에서 저장소를 찾는다 

basePackages  인수를 사용하여 이 동작을 변경할 수 있다

 

 

@Configuration
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
class MongoConfig {}

Spring Boot는 클래스 경로에서 Spring Data MongoDB를 찾으면 자동으로 이 작업을 수행한다.

 

 

https://github.com/eugenp/tutorials/tree/master/persistence-modules/spring-data-mongodb

 

GitHub - eugenp/tutorials: Just Announced - "Learn Spring Security OAuth":

Just Announced - "Learn Spring Security OAuth": . Contribute to eugenp/tutorials development by creating an account on GitHub.

github.com

 

728x90