본문 바로가기
Jpa

spring-boot Jpa 복합키 설정 Embedded

by 무대포 개발자 2020. 9. 6.
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> {
}


댓글