I need to save data in 2 tables (entity and association table). I just save my entity using a method save()from my object repository. Then for execution, I need to insert rows into the association table in native sql . Lines contain a link to a previously saved entity. The problem here: I get an integrity constraint exception regarding a foreign key. The first stored object is not known in this second query.
Here is my code:
Repo:
public interface DistributionRepository extends JpaRepository<Distribution, Long>, QueryDslPredicateExecutor<Distribution> {
@Modifying
@Query(value = "INSERT INTO DISTRIBUTION_PERIMETER(DISTRIBUTION_ID, SERVICE_ID) SELECT :distId, p.id FROM PERIMETER p "
+ "WHERE p.id in (:serviceIds) AND p.discriminator = 'SRV' ", nativeQuery = true)
void insertDistributionPerimeter(@Param(value = "distId") Long distributionId, @Param(value = "serviceIds") Set<Long> servicesIds);
}
Service:
@Service
public class DistributionServiceImpl implements IDistributionService {
@Inject
private DistributionRepository distributionRepository;
@Override
@Transactional
public DistributionResource distribute(final DistributionResource distribution) {
Distribution created = new Distribution();
final Date distributionDate = new Date();
created.setStatus(EnumDistributionStatus.distributing);
created.setDistributionDate(distributionDate);
created.setDistributor(agentRepository.findOne(distribution.getDistributor().getMatricule()));
created.setDocument(documentRepository.findOne(distribution.getDocument().getTechId()));
created.setEntity(entityRepository.findOne(distribution.getEntity().getTechId()));
created = distributionRepository.save(created);
final Set<Long> serviceIds = new HashSet<Long>();
for (final ServiceResource sr : distribution.getServices()) {
serviceIds.add(sr.getTechId());
}
distributionRepository.insertDistributionPerimeter(created.getId(), serviceIds);
}
}
The 2 queries seem to be in different transactions, while I set the annotation @Transactionnal. I also tried to execute my second request using entityManager.createNativeQuery()and got the same result ...