연관 관계 매핑 : 1대1 단방향 매핑 > 스프링 부트

본문 바로가기

[개발] 연관 관계 매핑 : 1대1 단방향 매핑

필기자
2022-11-07 12:16 5,311 0

본문

cart와 member 관계

 

20221107121421_b7e01d0501d844f992b5c6d5592b1e1a_dmq1.png

 

kr/hull/shop/entity/Cart.java 작성



@Entity
@Table(name = "cart")
@Getter
@Setter
@ToString
public class Cart {

    @Id
    @Column(name = "cart_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    //@OneToOne(fetch = FetchType.EAGER) //즉시 로딩 전략
    @OneToOne
    @JoinColumn(name="member_id")
    private Member member;

}

 

결과

 

20221107142801_b7e01d0501d844f992b5c6d5592b1e1a_2uxo.png

 

20221107142928_b7e01d0501d844f992b5c6d5592b1e1a_apyx.png

 

cart 기능 테스트

kr/hull/shop/repository/CartRepository.java 생성



public interface CartRepository extends JpaRepository<Cart, Long> {

}

 

20221107143518_b7e01d0501d844f992b5c6d5592b1e1a_fj2h.png

 

kr/hull/shop/entity/CartTest.java 파일 생성



@SpringBootTest
@Transactional
@TestPropertySource(locations="classpath:application-test.properties")
class CartTest {

    @Autowired
    CartRepository cartRepository;

    @Autowired
    MemberRepository memberRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @PersistenceContext
    EntityManager em;

    public Member createMember(){
        MemberFormDto memberFormDto = new MemberFormDto();
        memberFormDto.setEmail("test@email.com");
        memberFormDto.setName("홍길동");
        memberFormDto.setAddress("서울시 마포구 합정동");
        memberFormDto.setPassword("1234");
        return Member.createMember(memberFormDto, passwordEncoder);
    }

    @Test

    @Rollback(value = false)
    @DisplayName("장바구니 회원 엔티티 매핑 조회 테스트")
    public void findCartAndMemberTest(){
        Member member = createMember();
        memberRepository.save(member);
        Cart cart = new Cart();
        cart.setMember(member);
        cartRepository.save(cart);

        em.flush();
        em.clear();

        Cart savedCart = cartRepository.findById(cart.getId())
                .orElseThrow(EntityNotFoundException::new);
        assertEquals(savedCart.getMember().getId(), member.getId());
    }
}

 

결과 

 

20221107150747_b7e01d0501d844f992b5c6d5592b1e1a_dusb.png

 

20221107150812_b7e01d0501d844f992b5c6d5592b1e1a_wrau.png

 

20221107150858_b7e01d0501d844f992b5c6d5592b1e1a_eusp.png

 

20221107150944_b7e01d0501d844f992b5c6d5592b1e1a_1pd1.png

 

20221107151008_b7e01d0501d844f992b5c6d5592b1e1a_3dye.png

 

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색