May I use Spring Data JPA repository inside Java 8 forEach loop? Is it thread safe?
public interface MajorModOptRepository extends CrudRepository<MajorModOpt, Long> {
Set<MajorModOpt> findManyByManCodeAndModCode(String manCode, String modCode);
}
And here is the forEach loop:
@Component
public class MajorModOptsHelper {
@Autowired
private MajorModOptRepository majorModOptRepository;
public void setMajorOpts(@NonNull List<Vehicle> vehicles) {
vehicles.forEach(this::setMajorOpts);
}
// This method is called by above forEach
public void setMajorOpts(Vehicle vehicle) {
...
// Repository method is called here
Set<MajorModOptVO> knownOpts = majorModOptRepository.findManyByManCodeAndModCode(vehicle.getManCode(), vehicle.getModCode());
...
}
}
Thank you in advance.
It is tread save. There is no multi-threading involved.
The only thing you should take care about, is not to open an new transaction for each single findManyByManCodeAndModCode (except you want it). The most easy way to solve this, it to add an @Transactional to your setMajorOpts(@NonNull List<Vehicle> vehicles) method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With