Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- change_column_null
- Ruby on Rails
- 설치
- 정규식
- 우분투 24
- MySQL
- Kotlin
- install
- 차량번호찾기
- Rails
- Orange Pi 3B
- after_save
- Visual Studio Code
- Time.znoe.now
- 사용중인포트검색
- Migrate
- 도커
- Java
- docker
- change_column
- after_update
- 코틀린
- mac
- 주차장 시스템
- docket
- 쿠버네티스
- RUBY
- ubuntu
- 우분투
- 오랜지파이
Archives
- Today
- Total
중고 신입이 개발해보기..
Kotlin + Spring 환경에서 findById로 조회한 엔티티의 데이터를 수정하는 방법 by chatgpt 본문
Code Language/Kotlin
Kotlin + Spring 환경에서 findById로 조회한 엔티티의 데이터를 수정하는 방법 by chatgpt
rootkaien 2025. 6. 16. 14:13[질문] : Kotlin + Spring 환경에서 findById로 조회한 엔티티의 데이터를 수정하는 방법
[질문의도]: JPA 기반으로 특정 엔티티를 findById로 조회한 후, 해당 데이터를 수정하고 저장하는 실질적인 코드 플로우를 알고자 함
[응답]:
✅ 기본 흐름 요약
- Repository.findById()로 객체를 조회
- 조회된 엔티티의 필드를 수정
- 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()를 추천드립니다.
'Code Language > Kotlin' 카테고리의 다른 글
Ruby on Rails의 belongs_to -> kotlin by chatgpt (0) | 2025.06.16 |
---|---|
Kotlin에서 .let과 .apply의 차이점은 무엇인지? by chatGPT (2) | 2025.06.16 |
Kotlin에서 Entity 클래스를 정의할 때 클래스 바디 내부 방식과 주 생성자 방식의 구현 차이 by ChatGPT (1) | 2025.06.10 |
kotlin command line (0) | 2025.03.10 |
kotlin - basic - 1 (0) | 2025.02.24 |
Comments