如何遍历 Spring 数据 JPA 中实体的所有实例

How to iterate through all instances of an entity in Spring data JPA

我有一个名为 packet 的实体,我想更新该实体所有实例中的一个属性。我要更新的属性是给定百分比的数据包价格。

这是我的实体 class,它有控制器和服务 class:

@Entity
public class Packets {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    private String name;
    private BigDecimal packetPrice;

...constructors, getters, setters...et
)

这是我用于 @PutMapping 的 class:

@RestController
@RequestMapping(path = "changePrices")
public class ManipulatePrices {

    @Autowired
    PacketService packetService;

    @PutMapping(path = "minus/{percentage}")
    public void discount(@PathVariable("percentage") double percentage){
        percentage = (100 - percentage)/100;
        packetService.discount(percentage);
    }
}

这是PacketService中的方法class:

@Service
public class PacketService {

    private final PacketRepository packetRepository;
    
      public void discount(double percentage) {
        for(int i=0; i < packetRepository.count(); i++) {
            Packets packets = packetRepository.findAll().iterator().next();
            BigDecimal finalPrice = packets.getPacketPrice().multiply(BigDecimal.valueOf(percentage));
            packets.setPacketPrice(finalPrice);
            packetRepository.save(packets);
        }
    }

所以发生的事情是更改仅应用于数据包实体的第一个实例(id=1)。我如何遍历所有实例?

您可以将此方法添加到您的存储库中,它将修改数据包的所有条目 table :

@Transactional
@Modifying
@Query(value=" UPDATE Packets p SET p.packetPrice = :percentage/100 ")
//p.packetPrice = :percentage/100 is just for the sake of the example
//keep in mind the :percentage is refering to the method parameter
void discount(@Param("percentage") double percentage);

现在你在RestController的修改方法中调用这个方法

@PutMapping(path = "minus/{percentage}")
public void discount(@PathVariable("percentage") double percentage){
    percentage = (100 - percentage)/100;
    packetRepository.discount(percentage);
}
@Service
public class PacketService {

    private final PacketRepository packetRepository;
    
      public void discount(double percentage) {
        List<Packets> packets = packetRepository.findAll();
        List<Packets> newPackets = new ArrayList<>();
        for(int i=0; i < packetRepository.size(); i++) {
            Packets packet = packets.get(i);
            BigDecimal finalPrice = packet.getPacketPrice().multiply(BigDecimal.valueOf(percentage));
            packet.setPacketPrice(finalPrice);
            newPackets.add(packet);
        }
        packetRepository.save(newPackets);
    }

这样,你使用findAll()得到了列表;然后你遍历那个列表。在 newPackets 变量中,您将以新价格存储数据包。循环后,您将在单个查询中将整个列表存储在数据库中。这也会帮助您提高性能。