중고 신입이 개발해보기..

Kotlin + Spring 환경에서 findById로 조회한 엔티티의 데이터를 수정하는 방법 by chatgpt 본문

Code Language/Kotlin

Kotlin + Spring 환경에서 findById로 조회한 엔티티의 데이터를 수정하는 방법 by chatgpt

rootkaien 2025. 6. 16. 14:13

[질문] : Kotlin + Spring 환경에서 findById로 조회한 엔티티의 데이터를 수정하는 방법

[질문의도]: JPA 기반으로 특정 엔티티를 findById로 조회한 후, 해당 데이터를 수정하고 저장하는 실질적인 코드 플로우를 알고자 함


[응답]:

✅ 기본 흐름 요약

  1. Repository.findById()로 객체를 조회
  2. 조회된 엔티티의 필드를 수정
  3. Repository.save()로 저장

🔧 예제 코드

📁 Entity 예시

@Entity
class User(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,

    var name: String,
    var email: String
)

📁 Repository

interface UserRepository : JpaRepository<User, Long>

📁 Service 또는 사용 코드

@Service
class UserService(private val userRepository: UserRepository) {

    fun updateUserName(userId: Long, newName: String) {
        val user = userRepository.findById(userId).orElseThrow {
            IllegalArgumentException("User not found: $userId")
        }

        user.name = newName  // 엔티티 필드 수정

        userRepository.save(user)  // 변경된 내용 저장
    }
}

✅ 주의사항

항목설명

트랜잭션 서비스 메서드에 @Transactional을 붙이면, save 없이도 dirty checking으로 자동 저장됨
null 가능성 findById는 Optional 반환 → .orElseThrow {} 또는 orElse(null)로 처리 필요
save 필요 여부 Spring JPA는 기본적으로 변경 감지를 통해 자동 반영하지만, 명시적 save()가 안전함

✅ @Transactional 사용 예

@Transactional
fun updateUserEmail(userId: Long, newEmail: String) {
    val user = userRepository.findById(userId)
        .orElseThrow { IllegalArgumentException("User not found") }

    user.email = newEmail
    // save() 호출 없이도 트랜잭션 종료 시 자동 반영
}

✅ 결론 요약

단계설명

1. 조회 findById(id).orElseThrow { ... }
2. 수정 엔티티의 필드 값을 직접 변경
3. 저장 save(entity) 또는 @Transactional 이용 시 생략 가능

💡 save 생략 가능 여부는 트랜잭션 범위 내에 있는지에 달려 있습니다. 안정성을 위해 명시적 save()를 추천드립니다.

Comments