@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
@Entity
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String brand;
private double width;
private String typeFuel;
private double price;
@ManyToOne
@JoinColumn(name = "garage_id" , nullable = false)
private Garage garage;
@Version
private Long version;
}
@Transactional
public CarDto save(CreateCarCommand command) {
Garage garage = garageRepository.findWithLockingById(command.getGarageId())
.orElseThrow(() -> new EntityNotFoundException(MessageFormat
.format("Garage with id ={0} , not exist", command.getGarageId())));
if (garage.getNumberOfSpaces() <= garage.getCars().size()) {
throw new IllegalStateException("slot not available");
}
Car car = command.toEntity();
car.setGarage(garage);
return CarDto.fromEntity(carRepository.save(car));
}
REST API spring oobt , I have two entity Garage and Car , garage has numberOfSpaces , I need do locking beacuse if in the same time I send two request , created overbooking - numberOfSpaces 2 and size list 3 , how to impleement optimistic / pessimistic locking / transactional ? somone can help me on priv ?