I am trying to conditional insert operation to database (assume SQLite). My goal is to ensure data consistency.
Suppose we are making an appointment planner.
So we have an appointments table like this:
id
personal
appointment_date
However, we have an important rule. A person cannot make more than 3 appointments in the same day.
Normally we query from the database how many appointments this person has that day. Then we decide whether to insert or not. Right?
But let's say we have an API that gets a lot of traffic. Suppose two similar transactions started in the same millisecond and somehow the same person was given a 4th appointment. This is something we don't want.
I learned that to prevent this situation, a lock operation should be applied in the database. But I couldn't understand which lock type to apply. We know that deadlock can occur in pessimistic lock. Of course, we do not want this situation.
My question is, what should I do in Java Spring Boot to prevent this situation?
Entity:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Appointment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String person;
private Date appointment_date;
}
Service:
@Service
public class AppointmentService {
@Autowired
private AppointmentRepository appointmentRepository;
public Appointment saveAppointment(Appointment appointment) {
return appointmentRepository.save(appointment);
}
}
Repository:
@Repository
public interface AppointmentRepository extends JpaRepository<Appointment, Long> {
}
Controller:
@RestController
public class AppointmentController {
@Autowired
private AppointmentService appointmentService;
@PostMapping(“/store”)
public Appointment store(@RequestBody Appointment appointment) {
return appointmentService.saveAppointment(appointment);
}
}
Thank you very much for your attention :)