🐯[TIL] 250716-032

byoΒ·2025λ…„ 7μ›” 29일

πŸ’« JAVA

🏁 Event - Reservation

🌿 git

Event

@Entity
@Table(name = "events")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Event {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(name = "event_date", nullable = false)
    private LocalDateTime eventDate;

    private String location;

    @OneToMany(mappedBy = "event", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonManagedReference
    private List<Reservation> reservations = new ArrayList<>();
}

Reservation

@Entity
@Table(name = "reservations")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Reservation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String attendeeName;

    private int seat;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "event_id", nullable = false)
    @JsonBackReference
    private Event event;
}

EventDto

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class EventDto {
    @NotBlank(message = "이벀트λͺ…을 μž…λ ₯ν•©λ‹ˆλ‹€.")
    private String name;

    @NotNull(message = "이벀트 λ‚ μ§œλ₯Ό μž…λ ₯")
    private LocalDateTime eventDate;

    private String location;
}

ReservationDto

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ReservationDto {
    @NotBlank(message = "μ˜ˆμ•½μž 이름을 μž…λ ₯ν•˜μ„Έμš”")
    private String attendeeName;

    @Min(1)
    @NotNull(message = "μ’Œμ„ 수λ₯Ό μž…λ ₯ν•˜μ„Έμš”")
    private Integer seats;
}

EventRepository

public interface EventRepository extends JpaRepository<Event, Long>, JpaSpecificationExecutor<Event> {
}

ReservationRepository

public interface ReservationRepository extends JpaRepository<Reservation, Long> {
    Page<Reservation> findByEventId(Long eventId, Pageable pageable);
}

EventService

@Service
@RequiredArgsConstructor
@Transactional
public class EventService {
    private final EventRepository eventRepository;

    public Page<Event> search(String name, String location, LocalDateTime from, LocalDateTime to, Pageable pageable) {
        Specification<Event> specification = Specification.allOf();
        if (name != null) specification = specification.and((root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("name"), "%" + name + "%"));
        if (location != null) specification = specification.and((root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("location"), "%" + location + "%"));
        if (from != null) specification = specification.and(((root, query, criteriaBuilder) -> criteriaBuilder.greaterThanOrEqualTo(root.get("eventDate"), from)));
        if (to != null) specification = specification.and(((root, query, criteriaBuilder) -> criteriaBuilder.lessThanOrEqualTo(root.get("eventtDate"), to)));

        return eventRepository.findAll(specification, pageable);
    }

    public Event getById(Long id) {
        return eventRepository.findById(id).orElseThrow(() -> new NoSuchElementException("이벀트 μ—†μŒ"));
    }

    public Event create(Event event) {
        return eventRepository.save(event);
    }
}

ReservationService

@Service
@RequiredArgsConstructor
@Transactional
public class ReservationService {
    private final ReservationRepository reservationRepository;
    private final EventRepository eventRepository;

    public Page<Reservation> getByEvent(Long eventId, Pageable pageable) {
        return reservationRepository.findByEventId(eventId, pageable);
    }

    public Reservation create(Long eventId, ReservationDto reservationDto) {
        Event event = eventRepository.findById(eventId).orElseThrow(() -> new NoSuchElementException("이벀트 μ—†μŒ"));

        Reservation reservation = new Reservation();
        reservation.setEvent(event);
        reservation.setAttendeeName(reservationDto.getAttendeeName());
        reservation.setSeat(reservationDto.getSeats());

        return reservationRepository.save(reservation);
    }

    public Reservation update(Long id, ReservationDto reservationDto) {
        Reservation existReservation = reservationRepository.findById(id).orElseThrow(() ->  new NoSuchElementException("μ˜ˆμ•½ μ—†μŒ"));

        existReservation.setAttendeeName(reservationDto.getAttendeeName());
        existReservation.setSeat(reservationDto.getSeats());

        return reservationRepository.save(existReservation);
    }

    public void delete(Long id) {
        reservationRepository.deleteById(id);
    }
}

EventController

@RestController
@RequestMapping("/api/events")
@RequiredArgsConstructor
public class EventController {
    private final EventService eventService;

    @GetMapping
    public Page<Event> list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime from,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime to,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
            ) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("eventDate").ascending());
        return eventService.search(name, location, from, to, pageable);
    }

    @GetMapping("/{id}")
    public Event get(@PathVariable Long id) {
        return eventService.getById(id);
    }

    @PostMapping
    public Event create(@Valid @RequestBody EventDto eventDto) {
        return eventService.create(eventDto);
    }

    @PutMapping("/{id}")
    public Event update(@PathVariable Long id, @Valid @RequestBody EventDto eventDto) {
        return eventService.update(id, eventDto);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        eventService.delete(id);

        return ResponseEntity.noContent().build();
    }
}

ReservationController

@RestController
@RequiredArgsConstructor
public class ReservationController {
    private final ReservationService reservationService;

    @GetMapping("/api/events/{eventId}/reservations")
    public Page<Reservation> listByEvent(
            @PathVariable Long eventId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
        return reservationService.getByEvent(eventId, pageable);
    }

    @PostMapping("/api/events/{eventId}/reservations")
    public Reservation add(@PathVariable Long eventId, @Valid @RequestBody ReservationDto reservationDto) {
        return reservationService.create(eventId, reservationDto);
    }

    @PutMapping("/api/reservations/{id}")
    public Reservation update(@PathVariable Long id, @Valid @RequestBody ReservationDto reservationDto) {
        return reservationService.update(id, reservationDto);
    }

    @DeleteMapping("/api/reservations/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        reservationService.delete(id);

        return ResponseEntity.noContent().build();
    }
}
profile
πŸ—‚οΈ hamstern

0개의 λŒ“κΈ€