Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

마이페이지, 메인페이지 CRUD 페이지 추가 #59

Merged
merged 3 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.kernel360.main.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MainContoller {
@GetMapping("")
ResponseEntity<String> mainPage(){
return ResponseEntity.status(HttpStatus.OK).body("main page입니다.");
}
Comment on lines +9 to +14
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

커밋 새로해서 push 한 것에 반영되었습니다. pull 받는걸 깜빡하고 바로 올렸나 봅니다~ ㅠㅠ


}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Controller에서 ResponseEntity 사용 시, ApiResponse을 사용한 방식으로 처리하기로 얘기되었으니, 리팩토링 때는 그 방식으로 적용해주시면 좋을 것 같아요~! 예시 코드는 #56 PR 내용 참고해주시면 됩니다~!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다음번 커밋에 리팩토링 하겠습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.kernel360.mypage.controller;

import com.kernel360.member.dto.MemberDto;
import com.kernel360.member.service.MemberService;
import com.kernel360.product.dto.ProductDto;
import com.kernel360.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mypage")
@RequiredArgsConstructor
public class MyPageController {
private final MemberService memberService;
private final ProductService productService;
@GetMapping("/main")
ResponseEntity<Model> main(Model model) {
List<ProductDto> productDtoList = productService.getProductListOrderByViewCount();
String bannerImageUrl = "http://localhost:8080/bannersample.png";
String suggestImageUrl = "http://localhost:8080/suggestsample.png";
Comment on lines +25 to +26
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻


model.addAllAttributes(Map.of("Banner" , bannerImageUrl,
"Suggest", suggestImageUrl,
"Product", productDtoList));

return ResponseEntity.status(HttpStatus.OK).body(model);
}

@GetMapping("/member")
ResponseEntity<String> myInfo() {
return ResponseEntity.status(HttpStatus.OK).body("mypage 내정보 page입니다.");
}

@GetMapping("/car")
ResponseEntity<String> myCar() {
return ResponseEntity.status(HttpStatus.OK).body("mypage 차량정보 page입니다.");
}

@DeleteMapping("/member")
ResponseEntity<String> memberDelete(@RequestBody MemberDto memberDto) {
return ResponseEntity.status(HttpStatus.OK).body(memberDto.id() + " 회원이 탈퇴되었습니다.");
}

@PostMapping("/member")
ResponseEntity<String> memberInfoAdd(@RequestBody MemberDto memberDto) {
return ResponseEntity.status(HttpStatus.OK).body(memberDto.id() + "회원의 회원정보가 추가되었습니다.");
}

@PatchMapping("/member")
ResponseEntity<String> changePassword(@RequestBody MemberDto memberDto) {
return ResponseEntity.status(HttpStatus.OK).body(memberDto.id() + "회원의 비밀번호가 변경 되었습니다.");
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,11 @@ public List<ProductDto> getProductListByKeyword(String keyword) {

return products.stream().map(ProductDto::from).toList();
}

@Transactional(readOnly = true)
public List<ProductDto> getProductListOrderByViewCount(){
List<Product> products = productRepository.findAllByOrderByViewCountDesc();

return products.stream().map(ProductDto::from).toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.kernel360.mypage.controller;

import com.kernel360.member.service.MemberService;
import com.kernel360.product.dto.ProductDto;
import com.kernel360.product.service.ProductService;
import com.navercorp.fixturemonkey.FixtureMonkey;
import com.navercorp.fixturemonkey.api.introspector.*;
import com.navercorp.fixturemonkey.api.type.TypeReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.ui.Model;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(MyPageController.class)
class MyPageControllerTest {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext context;

@MockBean
private MemberService memberService;

@MockBean
private ProductService productService;

@MockBean
private Model model;
private FixtureMonkey fixtureMonkey;

@BeforeEach
void 준비(WebApplicationContext webApplicationContext) {
fixtureMonkey = FixtureMonkey.builder()
.objectIntrospector(new FailoverIntrospector(
Arrays.asList(
BuilderArbitraryIntrospector.INSTANCE,
FieldReflectionArbitraryIntrospector.INSTANCE,
ConstructorPropertiesArbitraryIntrospector.INSTANCE,
BeanArbitraryIntrospector.INSTANCE
)
))
.build();

mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
}

@Test
void 마이페이지_메인요청이왔을때_200요청과_응답이_잘반환되는지() throws Exception {
//given
List<ProductDto> productDtoList = fixtureMonkey.giveMeBuilder(ProductDto.class).sampleList(5);

//when
when(productService.getProductListOrderByViewCount()).thenReturn(productDtoList);

//then
mockMvc.perform(get("/mypage/main"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.Banner").value("http://localhost:8080/bannersample.png"))
.andExpect(jsonPath("$.Suggest").value("http://localhost:8080/suggestsample.png"))
.andExpect(jsonPath("$.Product", hasSize(5)));

verify(productService, times(1)).getProductListOrderByViewCount();
}


}
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package com.kernel360.brand.entity;

import com.kernel360.base.BaseEntity;
import com.kernel360.product.entity.Product;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
@Entity
@Table(name = "brand")
public class Brand extends BaseEntity {
Expand All @@ -18,6 +19,9 @@ public class Brand extends BaseEntity {
@Column(name = "brand_name", nullable = false, length = Integer.MAX_VALUE)
private String brandName;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "brand")
private List<Product> productList;

@Column(name = "description", length = Integer.MAX_VALUE)
private String description;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, the code appears to be fine with a few minor suggestions for improvement:

  1. In the import statements, make sure to organize them and remove any unused imports.
  2. Consider using specific annotations from JPA (such as @onetomany) instead of relying on vendor-specific annotations (e.g., jakarta.persistence.OneToMany).
  3. Add the @OrderBy annotation to specify the ordering of the products in the productList field if necessary.
  4. Ensure that the BaseEntity class is implemented correctly and provides the required functionality for your application.
  5. Consider adding appropriate validation annotations or constraints to ensure data integrity (e.g., validating the length of the brand name).

Here's an updated version of the code with the suggested improvements:

package com.kernel360.brand.entity;

import com.kernel360.base.BaseEntity;
import com.kernel360.product.entity.Product;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "brand")
public class Brand extends BaseEntity {

    @Column(name = "brand_name", nullable = false)
    private String brandName;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "brand")
    private List<Product> productList;

    @Column(name = "description", length = Integer.MAX_VALUE)
    private String description;

    // Constructors, getters, and setters

}

Remember to review the changes carefully and adapt them to your specific requirements.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@OnetoOne 기본은 Eager 로 되어 있습니다. null 관련 사항은 jpa프로그래밍 책 298쪽 내용 참고로 첨부하겠습니다. 저도 정확히 이해를 못했는데, 혹시 이해가 되시면 저도 설명 좀 부탁드리겠습니다.

image
image

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#59 (comment) 이쪽에 제 생각을 적어두었습니다

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.kernel360.carinfo.entity;

import com.kernel360.base.BaseEntity;
import com.kernel360.member.entity.Member;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
Expand All @@ -14,7 +15,11 @@ public class CarInfo extends BaseEntity {
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "car_info_id_gen")
@SequenceGenerator(name = "car_info_id_gen", sequenceName = "car_info_car_no_seq")
@Column(name = "car_no", nullable = false)
private Integer carNo;
private Long carNo;

@OneToOne
@JoinColumn(name = "member_no")
private Member member;

@Column(name = "car_brand")
private String carBrand;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kernel360.carinfo.repository;

import com.kernel360.carinfo.entity.CarInfo;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CarInfoRepository extends JpaRepository<CarInfo, Long> {
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.kernel360.member.entity;

import com.kernel360.base.BaseEntity;
import com.kernel360.carinfo.entity.CarInfo;
import com.kernel360.washinfo.entity.WashInfo;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
Expand All @@ -22,6 +24,12 @@ public class Member extends BaseEntity {
@Column(name = "id", nullable = false)
private String id;

@OneToOne(mappedBy = "member")
private CarInfo carInfo;

@OneToOne(mappedBy = "member")
private WashInfo washInfo;

@Column(name = "email", nullable = false)
private String email;

Expand All @@ -39,15 +47,17 @@ public static Member of(Long memberNo, String id, String email, String password,
return new Member(memberNo, id, email, password, gender, birthdate);
}

/** All Binding **/
/**
* All Binding
**/
private Member(
Long memberNo,
String id,
String email,
String password,
String gender,
LocalDate birthdate
) {
) {
this.memberNo = memberNo;
this.id = id;
this.email = email;
Expand All @@ -56,27 +66,35 @@ private Member(
this.birthdate = birthdate;
}

/** joinMember **/
public static Member createJoinMember(String id, String email, String password){
/**
* joinMember
**/
public static Member createJoinMember(String id, String email, String password) {

return new Member(id,email,password);
return new Member(id, email, password);
}

/** joinMember Binding **/
private Member(String id, String email, String password){
/**
* joinMember Binding
**/
private Member(String id, String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}

/** loginMember **/
public static Member loginMember(String id, String password){
/**
* loginMember
**/
public static Member loginMember(String id, String password) {

return new Member(id,password);
return new Member(id, password);
}

/** loginMember Binding **/
private Member(String id, String password){
/**
* loginMember Binding
**/
private Member(String id, String password) {
this.id = id;
this.password = password;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.kernel360.product.entity;

import com.kernel360.base.BaseEntity;
import com.kernel360.brand.entity.Brand;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
Expand All @@ -21,6 +22,10 @@ public class Product extends BaseEntity {
@Column(name = "product_name", nullable = false)
private String productName;

@ManyToOne
@JoinColumn(name = "brand_no")
private Brand brand;

@Column(name = "barcode")
private String barcode;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@
public interface ProductRepository extends JpaRepository<Product, Long> {
@Query(value = "SELECT * FROM Product WHERE product_name LIKE CONCAT('%', :keyword, '%') OR barcode LIKE CONCAT('%', :keyword, '%') OR description LIKE CONCAT('%', :keyword, '%')", nativeQuery = true)
List<Product> findByKeyword(@Param("keyword") String keyword);

List<Product> findAllByOrderByViewCountDesc();
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ public class WashInfo extends BaseEntity {
@Column(name = "wash_no", nullable = false)
private Integer washNo;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_no", nullable = false)
private Member memberNo;
private Member member;

@Column(name = "wash_count")
private Integer washCount;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kernel360.washinfo.repository;

import com.kernel360.washinfo.entity.WashInfo;
import org.springframework.data.jpa.repository.JpaRepository;

public interface WashInfoRepository extends JpaRepository<WashInfo, Long> {
}
Loading