랄라
SpringBoot JPA, Spring Data JPA 본문
Spring Boot JPA
springBoot 어플리케이션 내에서 JPA 를 사용할 수 있도록 자동설정된 기능
application.properties내에 DB연결정보를 작성해두면 자동으로 설정이 완료된다.
@Transactional
DB의 트랜젝션 개념을 손쉽게 적용할 수 있도록 SpringBoot JPA에서 제공하는 기능
트랜젝션이 종료되는 즉시 변경된 Entity가 자동으로 DB에 반영됨. (Commit 시점)
@Transactional //변경 감지(Dirty Checking)를 위해 필수
public Long updateData(Long id, DataDTO dataDto) {
// repository에서 조회된 값은 영속성 컨텍스트에 의해 관리되며, 해당 객체는 영속 상태로 관리됨
Data data = findData(id);
data.update(dataDto); //entity의 상태가 변경되어, 커밋시 자동으로 값 업데이트
return id; //업데이트 데이터 반환
}
*변경감지(Dirty Checking)
update() 메서드 호출 시 해당 객체의 속성값이 변경되며, JPA는 변경 감지(Dirty Checking)를 통해 이 객체의 변경 사항을 추적.
Spring Data JPA
JPA의 데이터베이스 상호작용을 돕는 라이브러리의 개념
Repository 인터페이스를 제공한다.
public interface Sample extends JpaRepository<SampleEntity, Long> {
//인터페이스에서 상속받아 사용가능
}
JPA Auditing
entity의 수정 및 생성등의 기록을 자동으로 인식
* Auditing 기능 사용시 주의사항
@EnableJpaAuditing //필수적용! - 미적용시 기능사용불가
@SpringBootApplication
public class SampleApplication{
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
사용방법
- 해당 timestamp 기능을 지닌 entity 생성한뒤 필요한 entity에서 상속받아 사용.
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Timestamped {
@CreatedDate
@Column(updatable = false)//최초생성에만 저장됨
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime createdAt;
@LastModifiedDate //변경이 생길때마다 시간 자동저장
@Column
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime modifiedAt;
}
Query Methods
메서드 이름으로 SQL을 생성할 수 있는 Query Methods 기능을 제공.
기본적으로 제공되는 메서드 외의 새로운 메서드 구현 시 사용.
정의되어있는 규칙에 맞추어 메서드 선언 시 해당 메서드를 자동으로 인식하여 SQL이 구현됨.
*query 구현 예시
public interface UserRepository extends Repository<User, Long> {
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
//select * from User where emailAddress = ?(emailAddress) and lastname = ?(lastname);
}
*관련사이트
JPA Query Methods :: Spring Data JPA
JPA Query Methods :: Spring Data JPA
By default, Spring Data JPA uses position-based parameter binding, as described in all the preceding examples. This makes query methods a little error-prone when refactoring regarding the parameter position. To solve this issue, you can use @Param annotati
docs.spring.io
'내일배움캠프 > 공부정리' 카테고리의 다른 글
| JWT(Json Web Token) (0) | 2025.02.04 |
|---|---|
| Cookie와 Session (0) | 2025.02.04 |
| Entity 와 Persistence Context (영속성 컨텍스트) (1) | 2025.02.04 |
| JDBC (+JdbcTemplate) (0) | 2025.02.04 |
| SQL (MYSQL 기준) (2) | 2025.02.04 |