온 코딩

[게시판] 필요한 입출력 메소드 만들기 본문

FINAL PROJECT

[게시판] 필요한 입출력 메소드 만들기

SummerON 2021. 7. 21. 19:31

+ 프로젝트 구조 수정 

출력값에 따른 DTO 클래스 추가

- AuctionList - Address 엔티티 one to one 관계 수정 ( Lazy, Cascade 추가)

    @OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL) //AuctionList 테이블과 1:1 관계
    @JoinColumn(name="auc_add")
    private AuctionList aucSeq;
    @OneToOne(mappedBy = "aucSeq",cascade = CascadeType.ALL,fetch = FetchType.EAGER) //Address 테이블과 1:1 관계
    private Address address;

출력 

한번에 출력할 값을 하나의DTO에 저장해야 함 

각각의 Entity에서 한번에 값을 불러온 후 (JPQL사용) 불러온 값에 맞는 DTO로 변환하여 출력처리 

 

상태 값 확인 필드 

AcutionList - state=0 : 경매 진행 중 / state=1 경매완료, 매칭미완료 / state=2 경매완료, 매칭완료

                / state=3 : 일 수행완료 / statea=4 : 경매삭제

BiddingList - chosen=0 : 미낙찰 / chose=1 : 낙찰 / chose=2 : 내역삭제

 

필요한 출력값 

- 로그인 한 유저가 등록한 경매 중 아직 매칭이 안 된 것 (auction.state = 0)

 : auction / address 테이블 조회

 

- 로그인 한 유저가 등록한 경매 중 경매가 끝났지만 매칭은 진행되지 않은 것 (auction.state = 1)

: auction / address 테이블 조회 

 

- 로그인 한 유저가 등록한 경매 중 매칭이 된 것 (auction.state = 2, bidding.chosen=1)

: auction/address/ bidding 테이블 조회 

 

- 로그인 한 유저가 등록한 경매 중 일 수행이 완료 된 것 ( auction.state = 3, bidding.chosen =1)

: auction/address/ bidding 테이블 조회

 

1. AuctionRepository

package com.finalp.hhw.repository.auction;

import com.finalp.hhw.entity.auction.*;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.*;
import org.springframework.stereotype.*;

@Repository
public interface AuctionListRepository extends JpaRepository<AuctionList, Long> {

    //test 1 : state=0, auctionList-User 출력
    @Query(value = "select a,b from AuctionList a LEFT JOIN a.id b where a.id='user2' and a.state=0")
    Page<Object[]> getAllWithState1(Pageable pageable);

    //test2  state=0(경매진행 중) , auctionList-Address 정보 출력
    //       state=1(경매완료, 매칭미완료) ,  regDate< now < doDateTime인 acutionList-Address
    @Query(value = "SELECT a,b from AuctionList a , Address b WHERE a.aucSeq = b.aucSeq and a.state=0 and a.id='user2'")
    Page<Object[]> getAllWithState2(Pageable pageable);

    //test3  state=2(매칭 완료), ischosen=1(낙찰값) , auctionList-Address-Bidding 정보 출력
    //       steat=3(일수행완료) auctionList-Address-Bidding
    @Query(value = "SELECT a,b,c from AuctionList a , Address b, BiddingList c WHERE a.aucSeq = b.aucSeq and a.state=2 and a.id='user3' and a.aucSeq = c.aucSeq and c.chosen =1")
    Page<Object[]> getAllWithState3(Pageable pageable);

    // 경매 삭제 시, bidding,auction 관련튜플 ischosen , state = 4
    
    // doDateTime < now 인 state=1 값이 있으면 강제로 state = 4로 바꾸는 메서드 필요

    // regDate + 1h < 0 and state=0 이 있으면 로딩 시 state=1 로 변경

    //aucSeq값으로 옥션 하나만 불러오기
    @Query(value = "select a from AuctionList a where a.aucSeq=:aucSeq")
    Object[] getAuctionWithId(@Param("aucSeq") Long aucSeq);
}

2. AuctionService 

package com.finalp.hhw.service.auction;

import com.finalp.hhw.dto.*;
import com.finalp.hhw.dto.auction.*;
import com.finalp.hhw.entity.auction.*;
import com.finalp.hhw.entity.user.*;

import java.util.*;

public interface AuctionService {

    //경매 등록
    Long register(AuctionListDTO dto, AddressDTO aDto);

    //경매 참여
    Long BiddingIn(BiddingListDTO dto);

    //입찰(선택)

    //경매삭제

    //경매조회
    /* 경매 조회 메소드
    진행 중 : state = 0;
    매칭 완료 : regDate+1h < x < doDateTime
    진행 완료 : doDateTime < x
    */
    //aucSe옥션 값 하나만 가져오기
    Optional<AuctionList> getAuction(Long no);

    //목록처리1 test :state = 0, Auction-User
    PageResultDTO<AuctionListDTO, Object[]> getList1(PageRequestDTO pageRequestDTO);

    //목록처리2 test :state = 0, Auction-Address
    PageResultDTO<AuctionAddressDTO, Object[]> getList2(PageRequestDTO pageRequestDTO);

    //목록처리3 test :state = 0, Auction-Address-Bidding
    PageResultDTO<AucAddBidDTO, Object[]> getList3(PageRequestDTO pageRequestDTO);

    //타이머 - 경매 남은 시간얻기
    long timer(Optional<AuctionList> auction);

    /**dtoToEntity : 입력 받은 값을 엔티티로 변환 후 DB전달 **/
    //AuctionList
    default AuctionList dtoToEntity(AuctionListDTO dto) {
        User user = User.builder().id(dto.getId()).build();

        AuctionList auctionList = AuctionList.builder().auctionGap(dto.getAuctionGap()).aucSeq(dto.getAucSeq()).age(dto.getAge()).category(dto.getCategory())
                .content(dto.getContent()).id(user).driverLicense(dto.getDriverLicense()).doDateTime(dto.getDoDateTime()).regDate(dto.getRegDate())
                .gender(dto.getGender()).level(dto.getLebel()).predictHour(dto.getPredicHour()).startPrice(dto.getStartprice()).title(dto.getTitle())
                .state(dto.getState()).build();
        return auctionList;
    }

    //BiddingList
    default BiddingList dtoToEntity(BiddingListDTO dto){
        User user = User.builder().id(dto.getId()).build();
        AuctionList auctionList = AuctionList.builder().aucSeq(dto.getAucSeq()).build();
        BiddingList biddingList = BiddingList.builder().bidSeq(dto.getBidSeq()).aucSeq(auctionList).id(user).chosen(dto.getChosen())
                .offerPrice(dto.getOfferPrice()).build();
        return biddingList;
    }

    //Address
    default Address dtoToEntity(AddressDTO dto){
        AuctionList auctionList = AuctionList.builder().aucSeq(dto.getAucSeq()).build();
        Address address = Address.builder().address(dto.getAddress()).sido(dto.getSido()).aucSeq(auctionList).addSeq(dto.getAddSeq()).sigungu(dto.getSigungu()).build();
        return address;
    }

    /** entityToDto DB에서 가져 온 값을 dto 전환 후 출력 **/
    //AuctionList,User
    default AuctionListDTO entityToDTO(AuctionList auc, User user){
        AuctionListDTO auctionListDTO = AuctionListDTO.builder().auctionGap(auc.getAuctionGap()).age(auc.getAge()).aucSeq(auc.getAucSeq())
                .category(auc.getCategory()).content(auc.getContent()).doDateTime(auc.getDoDateTime()).regDate(auc.getRegDate()).driverLicense(auc.getDriverLicense())
                .gender(auc.getGender()).id(user.getId()).lebel(auc.getLevel()).predicHour(auc.getPredictHour()).startprice(auc.getStartPrice()).state(auc.getState())
                .title(auc.getTitle()).aucSeq(auc.getAucSeq()).build();
        return auctionListDTO;
    }

    //AuctionList,Address,User
    default AuctionAddressDTO entityToDTO(AuctionList auc, Address add, User user){
        AuctionAddressDTO auctionAddressDTO = AuctionAddressDTO.builder().auctionGap(auc.getAuctionGap()).age(auc.getAge()).aucSeq(auc.getAucSeq())
                .category(auc.getCategory()).content(auc.getContent()).doDateTime(auc.getDoDateTime()).regDate(auc.getRegDate()).driverLicense(auc.getDriverLicense())
                .gender(auc.getGender()).id(user.getId()).lebel(auc.getLevel()).predicHour(auc.getPredictHour()).startprice(auc.getStartPrice()).state(auc.getState())
                .title(auc.getTitle()).aucSeq(auc.getAucSeq()).address(add.getAddress()).sido(add.getSido()).sigungu(add.getSigungu()).build();
        return auctionAddressDTO;
    }

    //AuctionList,Address
    default AuctionAddressDTO entityToDTO(AuctionList auc, Address add){
        AuctionAddressDTO auctionAddressDTO = AuctionAddressDTO.builder().auctionGap(auc.getAuctionGap()).age(auc.getAge()).aucSeq(auc.getAucSeq())
                .category(auc.getCategory()).content(auc.getContent()).doDateTime(auc.getDoDateTime()).regDate(auc.getRegDate()).driverLicense(auc.getDriverLicense())
                .gender(auc.getGender()).lebel(auc.getLevel()).predicHour(auc.getPredictHour()).startprice(auc.getStartPrice()).state(auc.getState())
                .title(auc.getTitle()).aucSeq(auc.getAucSeq()).address(add.getAddress()).sido(add.getSido()).sigungu(add.getSigungu()).build();
        return auctionAddressDTO;
    }

    //AuctionList,Address,User,BiddingList(User) - 추후 작성
    default AucAddBidDTO entityToDTO(AuctionList auc, Address add, BiddingList bid){
        String helper = bid.getId().getId().toString();
        AucAddBidDTO DTO = AucAddBidDTO.builder().auctionGap(auc.getAuctionGap()).age(auc.getAge()).aucSeq(auc.getAucSeq())
                .category(auc.getCategory()).content(auc.getContent()).doDateTime(auc.getDoDateTime()).regDate(auc.getRegDate()).driverLicense(auc.getDriverLicense())
                .gender(auc.getGender()).lebel(auc.getLevel()).predicHour(auc.getPredictHour()).startprice(auc.getStartPrice()).state(auc.getState())
                .title(auc.getTitle()).aucSeq(auc.getAucSeq()).address(add.getAddress()).sido(add.getSido()).sigungu(add.getSigungu())
                .chosen(bid.getChosen()).bidSeq(bid.getBidSeq()).hId(helper).offerPrice(bid.getOfferPrice()).build();
        return DTO;
    }

    //BiddingList
    default BiddingListDTO entityToDTO(BiddingList bid, AuctionList auc, User user){
        BiddingListDTO biddingListDTO = BiddingListDTO.builder().aucSeq(auc.getAucSeq()).id(user.getId()).bidSeq(bid.getBidSeq()).chosen(bid.getChosen())
                .offerPrice(bid.getOfferPrice()).build();
        return biddingListDTO;
    }

    //Address
    default AddressDTO entityToDTO(Address add , AuctionList auc){
        AddressDTO addressDTO = AddressDTO.builder().aucSeq(auc.getAucSeq()).address(add.getAddress()).addSeq(add.getAddSeq()).sigungu(add.getSigungu())
                .sido(add.getSido()).build();
        return addressDTO;
    }



}

3. AuctionServiceImpl

package com.finalp.hhw.service.auction;

import com.finalp.hhw.dto.*;
import com.finalp.hhw.dto.auction.*;
import com.finalp.hhw.entity.auction.*;
import com.finalp.hhw.entity.user.*;
import com.finalp.hhw.repository.auction.*;
import lombok.*;
import lombok.extern.log4j.*;
import org.springframework.data.domain.*;
import org.springframework.stereotype.*;

import java.text.*;
import java.time.*;
import java.util.*;
import java.util.function.*;

@Service
@Log4j2
@RequiredArgsConstructor
public class AuctionServiceImpl implements AuctionService{

    private final AuctionListRepository auctionListRepository;
    private final AddressRepository addressRepository;
    private final BiddingListRepository biddingListRepository;

    //경매 등록
    @Override
    public Long register(AuctionListDTO dto, AddressDTO aDto) {
        System.out.println("======= register ========");
        log.info(dto);

        Address address = dtoToEntity(aDto);
        AuctionList auctionList = dtoToEntity(dto);

        auctionList.setAddress(address);
        address.setAucSeq(auctionList);

        auctionListRepository.save(auctionList);
        return auctionList.getAucSeq();
    }

    //경매참여 - 비딩 입력
    @Override
    public Long BiddingIn(BiddingListDTO dto) {
        System.out.println("======== bidding in =========");
        log.info(dto);

        BiddingList biddingList = dtoToEntity(dto);
        biddingListRepository.save(biddingList);

        return biddingList.getBidSeq();
    }

    //auction객체 하나만 불러오기
    @Override
    public Optional<AuctionList> getAuction(Long no) {
        System.out.println("======== getAuction =========");
        Optional<AuctionList> auction = auctionListRepository.findById(no);
        return auction;
    }

    //목록처리1 test :state = 0, Auction-User
    @Override
    public PageResultDTO<AuctionListDTO, Object[]> getList1(PageRequestDTO pageRequestDTO) {
        log.info(pageRequestDTO);

        //정렬방식 설정
        Pageable pageable = pageRequestDTO.getPageable(Sort.by("aucSeq").descending());

        //검색 조건 처리 : 우선 없음
        //BooleanBuilder booleanBuilder = getSearch(PageRequestDTO);

        Page<Object[]> result = auctionListRepository.getAllWithState1(pageable);
        Function<Object[], AuctionListDTO> fn = (en -> entityToDTO((AuctionList)en[0],(User)en[1]));
        return new PageResultDTO<>(result, fn);
    }

    //목록처리2 test :state = 0, Auction-User-Address
    @Override
   public PageResultDTO<AuctionAddressDTO, Object[]> getList2(PageRequestDTO pageRequestDTO) {

        //정렬방식 설정
        Pageable pageable = pageRequestDTO.getPageable(Sort.by("aucSeq").descending());

        Page<Object[]> result = auctionListRepository.getAllWithState2(pageable);
        Function<Object[], AuctionAddressDTO> fn = (en -> entityToDTO((AuctionList)en[0],(Address)en[1]));
        // System.out.println(fn.toString());
        return new PageResultDTO<>(result, fn);
    }

    //목록처리3 test :state = 0, Auction-Address-Bidding
    @Override
    public PageResultDTO<AucAddBidDTO, Object[]> getList3(PageRequestDTO pageRequestDTO) {

        //정렬방식 설정
        Pageable pageable = pageRequestDTO.getPageable(Sort.by("aucSeq").descending());

        Page<Object[]> result = auctionListRepository.getAllWithState3(pageable);
        Function<Object[], AucAddBidDTO> fn = (en -> entityToDTO((AuctionList)en[0],(Address)en[1],(BiddingList)en[2]));
        // System.out.println(fn.toString());
        return new PageResultDTO<>(result, fn);
    }

    //타이머 - 경매 남은 시간얻기
    @Override
    public long timer(Optional<AuctionList> auction) {
        LocalDateTime time = auction.get().getRegDate(); // 등록시간 불러오기
        Date dTime = java.sql.Timestamp.valueOf(time); // 계산하기 위해 형 변형

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime(); // 지금 시간
        cal.setTime(dTime);
        cal.add(Calendar.HOUR, 1); // 등록시간 +1 : 경매 완료 시간
        Date endTime = cal.getTime();
        long sec = (endTime.getTime()-now.getTime())/1000; // 경매완료시간 - 지금시간 (초)
        return sec;
    }
}

4. AuctionRepositoryTest

package com.finalp.hhw.repository;

import com.finalp.hhw.entity.auction.*;
import com.finalp.hhw.entity.user.*;
import com.finalp.hhw.repository.auction.*;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;
import org.springframework.data.jpa.repository.config.*;
import org.springframework.transaction.annotation.*;

import java.time.*;
import java.util.*;
import java.util.stream.*;

@SpringBootTest
public class AuctionListRepositoryTest {

    @Autowired
    private AuctionListRepository auctionListRepository;

    @Test
    public void insertAuctionList(){
        User user = User.builder().id("user2").build();
        Address address = Address.builder().address("dlf dl tka ").sido("dlf ").sigungu("dl").build();
        AuctionList auctionList = AuctionList.builder().category(1).id(user).doDateTime(LocalDateTime.now()).predictHour("45m")
            .level(2).startPrice(10000).auctionGap(500).title("포린 테스트 ").content("포링ㄴㅇㅇㅇ ㅁ ").address(address).build();
        address.setAucSeq(auctionList);
        auctionListRepository.save(auctionList);
    }

    @Transactional //하나의 메서드를 하나의 트랜젝션으로 처리
    @Test
    public void testRead(){
        Optional<AuctionList> result = auctionListRepository.findById(30L);

        AuctionList auctionList = result.get();
        System.out.println(auctionList);
        System.out.println(auctionList.getAucSeq()+"  "+auctionList.getTitle());
    }
//AuctionList(aucSeq=27, category=1, doDateTime=2021-07-19T17:04:57.913, predictHour=1, level=1, startPrice=20000, auctionGap=1000, title=디티오, content=디티오어렵다, regDate=null, driverLicense=1, gender=1, age=0, state=0)
//27  디티오
/*AuctionList(aucSeq=30, category=4, doDateTime=2021-07-20T17:39:05.300, predictHour=2, level=1, startPrice=20000, auctionGap=100, title=새프, content=새로운 프로젝트, regDate=2021-07-20T17:39:05.422, driverLicense=1, gender=1, age=0, state=0)
30  새프*/
    @Test
    public void testReadWithId(){
        Object[] result = auctionListRepository.getAuctionWithId(30L);
        Object[] arr = (Object[]) result;
        System.out.println("==================");
        System.out.println(Arrays.toString(arr));
    }
//[AuctionList(aucSeq=27, category=1, doDateTime=2021-07-19T17:04:57.913, predictHour=1, level=1, startPrice=20000, auctionGap=1000, title=디티오, content=디티오어렵다, regDate=null, driverLicense=1, gender=1, age=0, state=0)]

}

5. AuctionServiceTest

package com.finalp.hhw.service;

import com.finalp.hhw.dto.*;
import com.finalp.hhw.dto.auction.*;
import com.finalp.hhw.entity.auction.*;
import com.finalp.hhw.service.auction.*;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;

import java.text.*;
import java.time.*;
import java.util.*;

@SpringBootTest
public class AuctionServiceTest {

    @Autowired
    private AuctionService auctionService;

    //경매등록 - AuctionRepositoryTest 참고
    @Test
    public void testRegister(){
        AddressDTO aDto = AddressDTO.builder().address("일 이 삼").sido("일").sigungu("이").build();
        AuctionListDTO dto = AuctionListDTO.builder().auctionGap(100).age(0).category(4).content("brnad new").doDateTime(LocalDateTime.now())
                .driverLicense(1).gender(1).id("user3").lebel(1).predicHour("2").title("newnew").startprice(20000).build();

        Long aucSeq = auctionService.register(dto,aDto);
    }

    //경매참여 - BiddingRepositoryTest 참고
    @Test
    public void testBiddingIn(){
        int startPrice = 20000;
        int auctionGap = 500;
        BiddingListDTO dto = BiddingListDTO.builder().aucSeq(30L).id("user4").offerPrice(startPrice-auctionGap).build();

        Long bidseq = auctionService.BiddingIn(dto);
    }

    //경매 남은 시간 확인 - 초
    @Test
    public void testTimerCheck(){
        Optional<AuctionList> dto = auctionService.getAuction(30L);
        LocalDateTime time = dto.get().getRegDate();
        Date dTime = java.sql.Timestamp.valueOf(time);

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        cal.setTime(dTime);
        cal.add(Calendar.HOUR, 1);
        Date endTime = cal.getTime();
        long sec = (endTime.getTime()-now.getTime())/1000;
        System.out.println(sec);
    }

    //목록처리 test :state = 0, Auction-User
    @Test
    public void testList1(){ //state가 0인 값
        PageRequestDTO pageRequestDTO = new PageRequestDTO();
        PageResultDTO<AuctionListDTO, Object[]> result = auctionService.getList1(pageRequestDTO);
        for(AuctionListDTO DTO: result.getDtoList()){
            System.out.println(DTO);
        }
    }

    //목록처리2 test :state = 0, Auction-Address
    @Test
    public void testList2(){ //state가 0인 값
        PageRequestDTO pageRequestDTO = new PageRequestDTO();
        PageResultDTO<AuctionAddressDTO, Object[]> result = auctionService.getList2(pageRequestDTO);
        for(AuctionAddressDTO DTO: result.getDtoList()){
            System.out.println(DTO);
        }
    }

    //목록처리3 test :state = 0, Auction-Address-Bidding
    @Test
    public void testList3(){ //state가 1인값
        PageRequestDTO pageRequestDTO = new PageRequestDTO();
        PageResultDTO<AucAddBidDTO, Object[]> result = auctionService.getList3(pageRequestDTO);
        System.out.println(result.getDtoList().size());
        for(AucAddBidDTO DTO: result.getDtoList()){
            System.out.println(DTO);
        }
    }


}

입력

입력은 모두 하나의 트랜젝션으로 처리해야함 

 

필요한 입력값 

- 로그인한 유저가 특정 경매에 대해 비딩리스트를 확인하고 하나 선택 

: state=0 -> state=3 or state=1 -> state=3 & chosen=0 -> chosen=1

 

- 로그인한 유저가 특정 경매를 삭제 

: chosen=0 -> chosen=3  & state=0 or 1 or 3 -> state=4 (state=2인 경우 삭제불가!)

 

- 로그인한 유저의 경매 중 매칭 미완료이지만 이미 시간이 지난 경매 삭제

: chosen=0 -> chosen=3  & state=2 -> state=4 * 페이지 로딩 시 자동 처리  

 

- 로그인한 유저의 경매 중 경매시간이 끝났지만 매칭이 안된 경매의 state변경 

: state =0 -> state =1 *페이지 로딩 시 자동 처리

 

1. BiddingListRepository

package com.finalp.hhw.repository.auction;

import com.finalp.hhw.entity.auction.*;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

@Repository
@Transactional
public interface BiddingListRepository extends JpaRepository<BiddingList, Long> {

    //옥션이 삭제된 경우 관련 경매내역은 chosen이 2으로 변경
    @Modifying
    @Query(value = "update BiddingList b set b.chosen=2 where b.aucSeq.aucSeq=:aucSeq")
    void deleteAuction(Long aucSeq);

}

2. AuctionListRepository

package com.finalp.hhw.repository.auction;

import com.finalp.hhw.entity.auction.*;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.*;
import org.springframework.stereotype.*;

@Repository
public interface AuctionListRepository extends JpaRepository<AuctionList, Long> {

    //test 1 : state=0, auctionList-User 출력
    @Query(value = "select a,b from AuctionList a LEFT JOIN a.id b where a.id='user2' and a.state=0")
    Page<Object[]> getAllWithState1(Pageable pageable);

    //경매 진행 중인 목록  state=0(경매진행 중) , auctionList-Address 정보 출력
    @Query(value = "SELECT a,b from AuctionList a , Address b WHERE a.aucSeq = b.aucSeq and a.state=0 and a.id='user2'")
    Page<Object[]> getAllWithState2(Pageable pageable);

    //경매 완료, 매칭미완료 값
    @Query(value = "SELECT a,b from AuctionList a , Address b WHERE a.aucSeq = b.aucSeq and a.state=1 and a.id='user2'")
    Page<Object[]> getAllWithState4(Pageable pageable);

    //매칭완료, 일 수행 전 값   state=2(매칭 완료), ischosen=1(낙찰값) , auctionList-Address-Bidding 정보 출력
    @Query(value = "SELECT a,b,c from AuctionList a , Address b, BiddingList c WHERE a.aucSeq = b.aucSeq and a.state=2 and a.id='user3' and a.aucSeq = c.aucSeq and c.chosen =1")
    Page<Object[]> getAllWithState3(Pageable pageable);

    //일 수행 완료 된 값 불러오기 steat=3(일수행완료) auctionList-Address-Bidding
    @Query(value = "SELECT a,b,c from AuctionList a , Address b, BiddingList c WHERE a.aucSeq = b.aucSeq and a.state=3 and a.id='user3' and a.aucSeq = c.aucSeq and c.chosen =1")
    Page<Object[]> getAllWithState5(Pageable pageable);

    // doDateTime < now 인 state=1 값이 있으면 강제로 state = 4로 바꾸는 메서드 필요
    @Query(value = "select a from AuctionList a where a.state=1")
    Page<AuctionList> ChangeState2(Pageable pageable);

    // regDate + 1h < 0 and state=0 이 있으면 로딩 시 state=1 로 변경
    @Query(value = "select a from AuctionList a where a.state=0")
    Page<AuctionList> ChangeState1(Pageable pageable);

    //aucSeq값으로 옥션 하나만 불러오기
    @Query(value = "select a from AuctionList a where a.aucSeq=:aucSeq")
    Object[] getAuctionWithId(@Param("aucSeq") Long aucSeq);
}

2. AuctionService

    //타이머 - 경매 남은 시간얻기
    long timer(Long aucSeq);

    //일 시작까지 남은 시간 구하기
    long leftTime(Long aucSeq);

    //경매시간 완료, 매칭 미완료 경매 state=1로 변경
    void changeState1(PageRequestDTO pageRequestDTO);

    //경매시간 완료, 매칭미완료, 일 시작시간 초과 경매 state=4로 변경
    void changeState2(PageRequestDTO pageRequestDTO);

    //일 수행 완료 후 state값 변경
    void jobDone(Long aucSeq);

3. AuctionServiceImpl

    //타이머 - 경매 남은 시간얻기
    @Override
    public long timer(Long aucSeq) {
        Optional<AuctionList> auction = this.getAuction(aucSeq);
        LocalDateTime time = auction.get().getRegDate(); // 등록시간 불러오기
        Date dTime = java.sql.Timestamp.valueOf(time); // 계산하기 위해 형 변형

        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime(); // 지금 시간
        cal.setTime(dTime);
        cal.add(Calendar.HOUR, 1); // 등록시간 +1 : 경매 완료 시간
        Date endTime = cal.getTime();
        long sec = (endTime.getTime() - now.getTime()) / 1000; // 경매완료시간 - 지금시간 (초)
        return sec;
    }

    //일 시작시간까지 남은 시간 구하기
    @Override
    public long leftTime(Long aucSeq) {
        Optional<AuctionList> auction = this.getAuction(aucSeq);
        LocalDateTime time = auction.get().getDoDateTime(); //일 시작 시간
        Date dTime = java.sql.Timestamp.valueOf(time);

        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime(); // 지금 시간

        long sec = dTime.getTime() - now.getTime() / 1000;
        // sec < 0 일 경우 일 시작시간이 지난 것 !

        return sec;
    }

    //경매시간 완료, 매칭 미완료 경매 state=1로 변경
    @Override
    public void changeState1(PageRequestDTO pageRequestDTO) {
        log.info(pageRequestDTO);

        //정렬방식 설정
        Pageable pageable = pageRequestDTO.getPageable(Sort.by("aucSeq").descending());

        Page<AuctionList> result = auctionListRepository.ChangeState1(pageable);
        Function<AuctionList, AuctionListDTO> fn = (en -> entityToDTO(en));

        PageResultDTO<AuctionListDTO, AuctionList> sResult = new PageResultDTO<>(result, fn);

        for(AuctionListDTO dto : sResult.getDtoList()){
            Long aucSeq = dto.getAucSeq();
            long getTimer = this.timer(aucSeq);
            long getLeftTime = this.leftTime(aucSeq);

            if(getTimer<0 && getLeftTime>0){
                AuctionList auctionList = dtoToEntity(dto);
                auctionList.changetState(1);
                auctionListRepository.save(auctionList);
            }
        }

    }

    //매칭미완료 경매 중 이미 일 시작 시간이 지난 경매 state=4로 변경 (삭제처리)
    @Override
    public void changeState2(PageRequestDTO pageRequestDTO) {
        log.info(pageRequestDTO);

        //정렬방식 설정
        Pageable pageable = pageRequestDTO.getPageable(Sort.by("aucSeq").descending());

        Page<AuctionList> result = auctionListRepository.ChangeState2(pageable);
        Function<AuctionList, AuctionListDTO> fn = (this::entityToDTO);

        PageResultDTO<AuctionListDTO, AuctionList> sResult = new PageResultDTO<>(result, fn);

        for(AuctionListDTO dto : sResult.getDtoList()){
            Long aucSeq = dto.getAucSeq();
            long getTimer = this.timer(aucSeq);
            long getLeftTime = this.leftTime(aucSeq);

            if(getTimer<0 && getLeftTime>0){
                AuctionList auctionList = dtoToEntity(dto);
                auctionList.changetState(4);
                auctionListRepository.save(auctionList);
            }
        }

    }

    // 일 수행 완료 후 state=3으로 변경
    @Override
    public void jobDone(Long aucSeq) {
        Optional<AuctionList> auction = this.getAuction(aucSeq);
        AuctionList auctionList = auction.get();
        auctionList.changetState(3);
        auctionListRepository.save(auctionList);
    }

4. AcutionServiceTest

    //경매삭제 AuctionList.state = 4 / BiddingList.chosen=2
    @Test
    public void testDeleteAuction(){
        Long aucSeq = 15L;
        auctionService.deleteAuction(aucSeq);
    }

    // 낙찰 AuctionList.state = 2 / BiddingList.chosen=1
    @Test
    public void testChooseBidding(){
        Long bidSeq = 16L;
        auctionService.chooseBidding(bidSeq);
    }

    //경매시간 완료, 매칭 미완료 경매 state=1로 변경
    @Test
    public void ChangeState1(){
        PageRequestDTO pageRequestDTO = new PageRequestDTO();
        auctionService.changeState1(pageRequestDTO);
    }

    //매칭미완료 경매 중 이미 일 시작 시간이 지난 경매 state=4로 변경 (삭제처리)
    @Test
    public void ChangeState2(){
        PageRequestDTO pageRequestDTO = new PageRequestDTO();
        auctionService.changeState2(pageRequestDTO);
    }

    //일 완료 후 state=3 (완료)로 변경
    @Test
    public void testJobDone(){
        auctionService.jobDone(31L);

 

사용의 용이성을 위해 타이머 조금 수정함


해결 해야 하는 문제점 

1. querydsl과 lombok / query annotation의 충돌 

2. 하나의 메소드로 만든 각종 기능들의 적용 방법 (ex.타이머,stateChange등)

3. 메소드 실행할 때 마다 state/chosen값에 따른 제약사항 넣기

4. jpql 사용 시 n+1문제 등 효율적이지 못함 

 

+ 검색은 view 쪽과 연결 후 구현 할 예정

+ 이미지 업로드 구현 전! view와 연결 후 구현 예정 

 

계획 중 중요한 부분 

1. 달력 + 시계 묶어서 LocalDateTime으로 전달

2. 지도 API에서 받은 정보 분리하여  adress 테이블에 저장

3. 유저 화면 만들 때 불러와야하는 다양한 리스트의 효율적 처리

 

 

 

Comments