Spring Data concurrency

旧巷老猫 提交于 2019-12-13 15:32:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!