#268 Code Review of a Ticket Creation Service
Perform a code review:
@Service
class TicketService {
@Autowired
public UserRepository userRepository;
@Autowired
public TicketRepository ticketRepository;
@Autowired
private NotificationService notificationService;
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(
propagation = Propagation.REQUIRES_NEW,
isolation = Isolation.REPEATABLE_READ
)
public String createTicket(String username, String password, String content) {
Collection<Ticket> tickets = ticketRepository.findByUsername(username);
boolean canCreateTicket = true;
for (Ticket ticket : tickets) {
if ("OPEN" == ticket.getStatus()) {
canCreateTicket = false;
}
}
if (!canCreateTicket) {
return "Can not create ticket";
}
long newTicketId = tickets.stream()
.map(Ticket::getId)
.max(Long::compare)
.map(maxTicketId -> maxTicketId + 1)
.orElse(1L);
Optional<User> userOptional = userRepository.findByUsernameAndPassword(username, password);
if (userOptional.get() == null) {
return "User not found or password is incorrect";
}
User user = userOptional.get();
Ticket newTicket = new Ticket(newTicketId, user, "OPEN", content);
ticketRepository.save(newTicket);
notificationService.sendNotification(newTicketId);
jdbcTemplate.execute(
("INSERT INTO public.ticket_history (ticket_id, status, created_by, created_at) "
+ "VALUES (%d, '%s', '%s', CURRENT_TIMESTAMP)")
.formatted(newTicket.getId(), "OPEN", username)
);
return "OK";
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor