// 거래 체결
@Transactional
public Contract save(ContractAddDTO contractDto) {
Contract contract = new Contract();
// product 객체 설정
Product product = productRepository.findById(contractDto.getProductId())
.orElseThrow(()->new IllegalArgumentException("상품 아이디를 찾을 수 없습니다."));
contract.setProduct(product);
// buying 객체 설정, nullable
Optional<Buying> buying = buyingRepository.findById(contractDto.getBuyingId());
if(buying.isPresent()) {
contract.setBuying(buying.get());
} else {
contract.setBuying(null);
}
// selling 객체 설정, nullable
Optional<Selling> selling = sellingRepository.findById(contractDto.getSellingId());
if(selling.isPresent()) {
contract.setSelling(selling.get());
} else {
contract.setSelling(null);
}
// 나머지
contract.setBuyerNumber(contractDto.getBuyerNumber());
contract.setSellerNumber(contractDto.getSellerNumber());
contract.setContractDate(LocalDateTime.now());
contract.setSellingStatus(contractDto.getSellingStatus());
contract.setBuyingStatus(contractDto.getBuyingStatus());
contract.setPrice(contractDto.getPrice());
contract.setRegistDate(LocalDateTime.now());
return contractRepository.save(contract);
}
optional 설정을 했으니 null값이 들어와도 문제 없는줄 알았음.
but findById(null)을 하게 되니 거기서 그냥 멈춰버린듯...
if(contractDto.getBuyingId() != null) {
Optional<Buying> buying = buyingRepository.findById(contractDto.getBuyingId());
if(buying.isPresent()) {
contract.setBuying(buying.get());
} else {
contract.setBuying(null);
}
}
if(contractDto.getSellingId() != null) {
Optional<Selling> selling = sellingRepository.findById(contractDto.getSellingId());
if(selling.isPresent()) {
contract.setSelling(selling.get());
} else {
contract.setSelling(null);
}
}
이렇게 수정하고 해결됨