Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it thread safe to use Spring Data JPA repository inside Java 8 forEach loop?

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.

like image 928
Vojtech Avatar asked Jun 06 '26 01:06

Vojtech


1 Answers

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.

like image 191
Ralph Avatar answered Jun 07 '26 21:06

Ralph