가자공부하러!

Hibernate(13) - 연관관계 매핑 연습 본문

공부/Java

Hibernate(13) - 연관관계 매핑 연습

오피스엑소더스 2019. 12. 24. 16:06

1. 조건

 > 하나의 Market 엔티티는여러 개의 MarketEmployee 엔티티와 MarketItem 엔티티를 갖는다.

 

2. 목표

 > Market, MarketEmployee, MarketItem CRUD 프로그램 작성을 통해 Hibernate 연관관계 매핑 연습

 

3. 코드

 > Entity

@Entity
@Table(name = "market")
@Getter
@Setter
@ToString
public class Market {

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

  private String name;

  @OneToMany(mappedBy = "market", cascade = CascadeType.ALL)
  private Set<MarketEmployee> employees = new LinkedHashSet();

  @OneToMany(mappedBy = "market", cascade = CascadeType.ALL)
  private Set<MarketItem> items = new LinkedHashSet();
}

@Entity
@Table(name = "market_employee")
@Getter
@Setter
@ToString(exclude = "market")
public class MarketEmployee {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "market_employee_id")
  private Long id;

  private String name;
  private Integer age;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "market_id")
  private Market market;
}

@Entity
@Table(name = "market_item")
@Getter
@Setter
@ToString(exclude = "market")
public class MarketItem {

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

  private String name;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "market_id")
  private Market market;
}

 > 컨트롤러

@Slf4j
@RestController
@RequestMapping(value = "/market")
@AllArgsConstructor
public class MarketRestController {

  private final MarketRepository marketRepository;

  @RequestMapping(value = "/conn", method = RequestMethod.POST)
  public void chkConnection() {
    log.info("chk connection ok");
  }

  @RequestMapping(value = "/create", method = RequestMethod.POST)
  public void createMarket() {

    Market market = new Market();
    market.setName("시장1");
    market.setEmployees(new LinkedHashSet());
    market.setItems(new LinkedHashSet());

    for (int i = 1; i < 5; i++) {
      MarketEmployee emp = new MarketEmployee();
      emp.setName("직원" + i);
      emp.setMarket(market);
      market.getEmployees().add(emp);

      MarketItem item = new MarketItem();
      item.setName("물건" + i);
      item.setMarket(market);
      market.getItems().add(item);
    }

    marketRepository.save(market);

  }

  @RequestMapping(value = "/getall", method = RequestMethod.POST)
  public void getAllMarket() {
    List<Market> all = marketRepository.findAll();
    for (Market market1 : all) {
      log.info("market info : {}", market1);
    }
  }
}

 > 테스트

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MarketTest {

  @Rule
  public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
  @Autowired
  private WebApplicationContext context;
  private MockMvc mockMvc;
  private RestDocumentationResultHandler document;

  @Before
  public void setUp() {
    this.document = document(
        "{class-name}/{method-name}", preprocessResponse(prettyPrint())
    );
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
        .apply(documentationConfiguration(this.restDocumentation))
        .alwaysDo(document)
        .build();
  }

  @Test
  @Rollback(false)
  public void a_createMarket() throws Exception{
    mockMvc.perform(post("/market/create")).andDo(print());
  }

  @Test
  public void b_getAllMarketInfo() throws Exception{
    log.info("start get all ");
    mockMvc.perform(post("/market/getall")).andDo(print());
  }
}

 

4. 결과

 > insert는 잘 들어감

 > findAll 할 때 쿼리가 세개로 쪼개져서 나옴

 

5. 추가

 > findAll 세개로 쪼개져 나오는 쿼리를 하나로 묶고싶다.

 > 아니다 쪼개져서 나오는게 맞다.

  - 만약 하나로 하게되면 값들이 중복으로 나오게 되고 그 값들을 받을 수 있는 VO나 DTO를 하나 더 만들어야된다 -> 패스

Comments