Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- calendar
- values()
- 벌크연산
- 페이징
- 프로젝트생성
- Hibernate
- jQueryUI
- namedQuery
- joinfetch
- JPA
- Generic
- LIST
- fetchjoin
- JPQL
- JQuery
- 대량쿼리
- javascriptcalendar
- springflow
- 자바서블릿
- jscalendar
- 스프링데이터흐름
- 제네릭
- jQuery값전송
- 페치조인
- fullcalendar
- jQuery값전달
- 제너릭
- javaservlet
- 엔티티직접사용
- paging
Archives
- Today
- Total
가자공부하러!
Hibernate(13) - 연관관계 매핑 연습 본문
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를 하나 더 만들어야된다 -> 패스
'공부 > Java' 카테고리의 다른 글
모던자바인액션(CH2) - 동작 파라미터화 코드 전달 (0) | 2020.03.29 |
---|---|
모던자바인액션(CH1) - 자바8부터 추가된 것들 (0) | 2020.03.29 |
Spring Boot 테스트 활용(1) - JUnit 기초 환경설정 (0) | 2019.12.23 |
JUnit test 메소드 실행 순서 설정 (0) | 2019.12.23 |
QueryDSL 간단 예제(1) - select, update (2) | 2019.12.18 |
Comments