Java Spring数据并发
我想同时从H2数据库获取数据。我想通过并行流来做,但我用并行流得到了错误的结果。对于普通流,它返回正确的结果(只有一个SELECT返回结果,其他返回null)。我找不到问题出在哪里。我看起来像是在并发访问存储库。你能帮忙吗 实体:Java Spring数据并发,java,spring,spring-data,java-stream,Java,Spring,Spring Data,Java Stream,我想同时从H2数据库获取数据。我想通过并行流来做,但我用并行流得到了错误的结果。对于普通流,它返回正确的结果(只有一个SELECT返回结果,其他返回null)。我找不到问题出在哪里。我看起来像是在并发访问存储库。你能帮忙吗 实体: @Entity public class Car { @Id private String carType; public String getCarType() { return carType; } pu
@Entity
public class Car {
@Id
private String carType;
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
}
存储库:
@org.springframework.stereotype.Repository
public interface CarsRepository extends Repository<Car, String> {
void save(Car car);
Car findOneByCarType(String carType);
}
@org.springframework.stereotype.Repository
公共接口CarsRepository扩展存储库{
无效保存(汽车);
carfindonebycartype(字符串carType);
}
服务:
@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());
}
}
@服务
公共类CarsServiceImpl实现CarsService{
@自动连线
私家车储蓄车储蓄;
@凌驾
公共空间拯救(汽车){
carsRepository.save(car);
}
@凌驾
公共列表车辆(列表车辆){
返回carsTypes.parallelStream()
.map(carType->Optional.ofNullable(carsRepository.findOneByCarType(carType)))
.filter(可选::isPresent)
.map(可选::get)
.collect(Collectors.toList());
}
}
测试:
@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());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@交易的
@SpringApplicationConfiguration(类=Application.class)
公共类汽车服务测试{
@自动连线
私家车服务;
@试验
公共车辆{
列表carsTypes=Arrays.asList(“奥迪”、“福特”、“欧宝”);
弗雷赫石首鱼(
carType->{
汽车=新车();
car.setCarType(carType);
carsService.save(汽车);
}
);
List cars=carsService.getCars(carsTypes);
Assert.assertEquals(carsTypes.size(),cars.size());
}
}
实际问题是什么?此测试在并行流上失败,但在顺序流上有效?是。我认为并发访问不应该有问题,但有问题,我不知道为什么…什么是“错误的结果”?正如您所看到的。我有三辆车。当我试图让他们从平行流,我只有一辆车。其他则为空。当我在顺序流中运行它时,我得到了预期的三个CAR。只有主线程返回结果,当我在单独的线程池中运行代码时,什么也不返回。可能是竞争条件,因为某些组件(实体管理器?)不是线程安全的。