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 2 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,10 +1,9 @@
package com.kernel360.auth.repository;

import com.kernel360.auth.entity.Auth;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AuthRepository extends JpaRepository <Auth, Id> {
public interface AuthRepository extends JpaRepository <Auth, Long> {
Copy link
Collaborator

Choose a reason for hiding this comment

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

JpaRepository의 <> 매개변수중 Id는 기본적으로 Long 타입인데, Long으로 바꾸신 이유가 무엇인지 궁금합니다.
참고로 리포지터리에 Id라고 명시하면 엔티티의 @id 애노테이션이 부여된 필드를 바라보게 되어있는걸로 알고있는데, 제가 잘못알고있으면 교정 부탁드립니다.
image

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

오 하나 배웠네요~ 몰랐습니다


Auth findOneByMemberNo(Long memberNo);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +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
Copy link
Collaborator

Choose a reason for hiding this comment

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

entity에서 setter는 꼭 없애주세요

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

반영했습니다. Setter는 JPA buddy 작성과정에서 생긴것으로 보입니다. 각 도메인에서 필요없으시면 각자 삭제해주시면 될거 같습니다.

@Entity
Expand All @@ -18,6 +21,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
@JoinColumn(name = "member_no", nullable = false)
Copy link
Collaborator

Choose a reason for hiding this comment

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

@ OneToOne → 즉시로딩(EAGER), nullable = false → 내부조인인데 member 정보를 가져오지 못하는 경우가 생길 수도 있을 것 같아요..!
이건 근데 제가 확인해보진 못한 부분이라 추후 테스트코드를 통해 확인이 필요해보입니다!

Copy link
Collaborator

Choose a reason for hiding this comment

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

원투원은 기본 속성이 즉시로딩인건가요? join명세에서 nullable false일 경우 무조건 데이터를 가지고 있어야 한다로 추측이 되는데 발생하는 부작용이 어떤 것인지 자세한 설명을 듣고싶습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Copy link
Collaborator

Choose a reason for hiding this comment

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

확인해보니 지연 로딩을 방지하기위해 조회시 무조건 다 가져오는 구조이네요 프론트분하고 의논해서 판단했을 때 부가정보 등록페이지 접근시 맴버와 부가정보를 같이 가져 올 필요가 없다면 연관관계 맵핑을 수정해서 별도로 조회하게끔 해도 된다 보여집니다.

private Member memberNo;
private Member member;
Copy link
Collaborator

Choose a reason for hiding this comment

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

✔️


@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