728x90
반응형
spring-boot Jpa 복합키 설정 Embedded
- spring-boot 에서 Jpa 복합키를 설정. Embedded 방식으로.
@Entity
@Getter
@Setter
@NoArgsConstructor
public class CompositeDomain {
@EmbeddedId
private EmbeddedDomain embeddedDomain;
private String content;
}
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@NoArgsConstructor
public class EmbeddedDomain implements Serializable {
private String pk1;
private String pk2;
@Builder
public EmbeddedDomain(String pk1, String pk2) {
this.pk1 = pk1;
this.pk2 = pk2;
}
}
import org.example.jpa.domain.CompositeDomain;
import org.example.jpa.domain.EmbeddedDomain;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CompositeDomainRepositoryTest {
@Autowired
private CompositeDomainRepository compositeDomainRepository;
@Test
public void compositeDomainRepositoryTest() {
//given
String pk1 = "aaa";
String pk2 = "bbb";
EmbeddedDomain embeddedDomain = EmbeddedDomain.builder()
.pk1(pk1)
.pk2(pk2)
.build();
CompositeDomain compositeDomain = new CompositeDomain();
compositeDomain.setEmbeddedDomain(embeddedDomain);
compositeDomain.setContent("content123");
compositeDomainRepository.save(compositeDomain);
//when
Optional<CompositeDomain> result = compositeDomainRepository.findById(embeddedDomain);
//then
assertThat(result.get().getContent(), is("content123"));
}
}
import org.example.jpa.domain.CompositeDomain;
import org.example.jpa.domain.EmbeddedDomain;
import org.example.jpa.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CompositeDomainRepository extends JpaRepository<CompositeDomain, EmbeddedDomain> {
}
'Jpa' 카테고리의 다른 글
엔티티 매니저 왜 thread-safe 하도록 해야하는지? (0) | 2020.11.18 |
---|---|
MyBatis, Jpa 2개를 동시에 처리하는 트랜잭션 매니저 (0) | 2020.10.21 |
spring boot, jpa save 동작 원리 (merge, persist) (0) | 2020.07.25 |
spring-boot, Jpa 정리 - Transaction 묶음 (0) | 2020.07.11 |
spring-boot, Jpa 정리 - Integrate test (Jpa 통합 테스트) (0) | 2020.07.11 |
댓글