Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
@Getter
@NoArgsConstructor
public class AttachmentMapping extends BaseEntity {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "attachment_id")
@OneToOne(fetch = FetchType.LAZY, mappedBy = "attachmentMapping", cascade = CascadeType.ALL, orphanRemoval = true)
private FileAttachment fileAttachment;

@Enumerated(EnumType.STRING)
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/back/domain/file/entity/FileAttachment.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ public class FileAttachment extends BaseEntity {
@JoinColumn(name = "uploaded_by")
private User user;

@OneToMany(mappedBy = "fileAttachment", cascade = CascadeType.ALL, orphanRemoval = true)
private List<AttachmentMapping> attachmentMappings = new ArrayList<>();
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "attachmentMapping_id")
private AttachmentMapping attachmentMapping;

public FileAttachment(
String storedName,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.back.domain.file.repository;

import com.back.domain.file.entity.AttachmentMapping;
import com.back.domain.file.entity.EntityType;
import com.back.domain.file.entity.FileAttachment;
import jakarta.persistence.EntityManager;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;


import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
@Transactional
class AttachmentMappingRepositoryTest {
@Autowired
private FileAttachmentRepository fileAttachmentRepository;
@Autowired
private AttachmentMappingRepository attachmentMappingRepository;
@Autowired
private EntityManager em;

@Test
void AttachmentMapping_삭제시_FileAttachment_자동삭제_확인() throws Exception {
// given
FileAttachment fileAttachment = new FileAttachment(
"test",
new MockMultipartFile("test", "test", "image", "test".getBytes()),
null,
"test.URL"
);
fileAttachmentRepository.save(fileAttachment);
System.out.println("현재 저장된 파일 개수 : " + fileAttachmentRepository.findAll().size());

AttachmentMapping attachmentMapping = new AttachmentMapping(
fileAttachment,
EntityType.POST,
1L
);
attachmentMappingRepository.save(attachmentMapping);

// when
attachmentMappingRepository.deleteAllByEntityTypeAndEntityId(EntityType.POST, 1L);

em.flush(); // 즉시 DB에 변경사항 반영
em.clear(); // 영속성 컨텍스트 초기화

// then
assertThat(fileAttachmentRepository.findAll().size()).isEqualTo(0);
}
}