| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- LinkedList
- spring boot
- 백엔드스쿨
- ORM
- restTemplate
- 프로그래머스
- SpringSecurity
- JPA
- 스프링부트
- queue
- 백준
- JWT
- error
- 핵심가이드
- 백엔드
- 컴퓨터 구조
- 컴퓨터 공학
- 백엔드공부
- actuator
- array
- 연관관계
- SpringBoot
- spring
- 자료구조
- TestCode
- 제로베이스
- QueryDSL
- 개발자
- 서버
- Java
Archives
- Today
- Total
be_better
[JPA] @ManyToOne 연관관계에 따른 데이터베이스 오류 본문
목차
에러 내용
프로젝트 진행 중에 하나의 User(유저)에 여러 개의 Shop(상점)을 등록해두기 위해 Shop Entity에 @ManyToOne 단방향 연관관계를 설정해두었다.
@Entity
public class Shop extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 상점을 등록한 유저 id
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "owner_id")
@ToString.Exclude
private User owner;
}
ShopServiceImpl에 deleteShop() 구현
@Override
@Transactional
public ShopDeleteResponse deleteShop(Long shopId, ShopDeleteRequest request) {
log.info("[deleteShop] 상점 삭제 - 상점 id : {}", shopId);
// 상점 삭제
shopRepository.deleteById(shopId);
log.info("[deleteShop] 삭제 완료");
return ShopDeleteResponse.from(
ShopDto.builder()
.id(shopId)
.build()
);
}
이와 같은 코드를 짜고 postman으로 테스트를 했는데
Shop Table에 foreign key로 저장되어있던 User 정보까지 같이 삭제되는 현상이 있다.
해결
외래키 제약 조건에 의해 데이터베이스에서 오류가 난것이다.
정상적으로 동작시키기 위해
Shop Entity에서 Owner(User) 정보를 null 로 set 한 다음
Shop을 삭제해주면 해결!
@Override
@Transactional
public ShopDeleteResponse deleteShop(Long shopId, ShopDeleteRequest request) {
log.info("[deleteShop] 상점 삭제 - 상점 id : {}", shopId);
Shop shop = shopRepository.findById(shopId)
.orElseThrow(() -> new BaseException(SHOP_NOT_FOUND));
// 상점 삭제
shop.setOwner(null); // 추가한 내용
shopRepository.deleteById(shopId);
log.info("[deleteShop] 삭제 완료");
return ShopDeleteResponse.from(
ShopDto.builder()
.id(shopId)
.build()
);
}'JPA' 카테고리의 다른 글
| [JPA] JPA를 사용해야 하는 이유 (0) | 2023.06.12 |
|---|