问题
I want to get data from H2 database concurrently. I wanted to do it through parallel stream, but I am getting wrong results with parallel stream. With normal stream it returns right result (only one SELECT returns result others returns null). I am not able to find where is the problem. I look like in concurrent access to repository. Can you help?
Entity:
@Entity
public class Car {
@Id
private String carType;
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
}
Repository:
@org.springframework.stereotype.Repository
public interface CarsRepository extends Repository<Car, String> {
void save(Car car);
Car findOneByCarType(String carType);
}
Service:
@Service
public class CarsServiceImpl implements CarsService {
@Autowired
private CarsRepository carsRepository;
@Override
public void save(Car car) {
carsRepository.save(car);
}
@Override
public List<Car> getCars(List<String> carsTypes) {
return carsTypes.parallelStream()
.map(carType -> Optional.ofNullable(carsRepository.findOneByCarType(carType)))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
}
Test:
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@SpringApplicationConfiguration(classes = Application.class)
public class CarsServiceTest {
@Autowired
private CarsService carsService;
@Test
public void getCars() {
List<String> carsTypes = Arrays.asList("audi", "ford", "opel");
carsTypes.forEach(
carType -> {
Car car = new Car();
car.setCarType(carType);
carsService.save(car);
}
);
List<Car> cars = carsService.getCars(carsTypes);
Assert.assertEquals(carsTypes.size(), cars.size());
}
}
来源:https://stackoverflow.com/questions/34481577/spring-data-concurrency