I need to update all entities which filter by ID and I could do this for single entity and it works fine but how can I do this for multiple entities.
Here is successful example for single one to one update
@Override
public FullPack updatePack(FullPack fullPack, int id) {
FullPack newFullPack = fullPackRepository.findByPackId(id);
newFullPack.setPackCompose(fullPack.getPackCompose());
newFullPack.setPackSequence(fullPack.getPackPackSequence());
FullPack savedFullPack = fullPackRepository.save(newFullPack);
return savedFullPack;
}
Assume that I will get multiple FullPack based on findByPackId then how can I update all
@Override
public List<FullPack> updatePack(FullPack fullPack, int id) {
List<FullPack> newFullPack = fullPackRepository.findByPackId(id);
//////////////////
/////////////////
}
How can I do this kind of scenario
Iterate the list with a for loop:
@Override
public List<FullPack> updatePack(FullPack fullPack, int id) {
List<FullPack> newFullPackList = fullPackRepository.findByPackId(id);
for (FullPack newFullPack : newFullPackList) {
newFullPack.setPackCompose(fullPack.getPackCompose());
newFullPack.setPackSequence(fullPack.getPackPackSequence());
}
fullPackRepository.saveAll(newFullPackList);
return newFullPackList;
}
With JPA, most, in not all Repository interfaces exposes a .saveAll()
method that opens a path for you to save a collection.
You can simply save multiple FullPack like so.
@Override
public List<FullPack> updatePack(FullPack fullPack, int id) {
List<FullPack> newFullPack = fullPackRepository.findByPackId(id);
...
fullPackRepository.saveAll(newFullPack)
}
you can do it with a Repository
@Query("update OrdineMacchina o set o.durataEsecuzione = o.durataEsecuzione + :incremento where o.idOrdineMacchina = :idOrdineMacchina")
@Modifying
void updateDuration(@Param("idOrdineMacchina") Long idOrdineMacchina,@Param("incremento") Integer incremento);
don't foreget @Modifing. You have to @autowire the repository where you need the update. You can write the query in JPQL or as a native query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.