我有一個名為資料包的物體,我想在該物體的所有實體中更新一個屬性。我要更新的屬性是給定百分比的資料包價格。
這是我的物體類,它有控制器和服務類:
@Entity
public class Packets {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
private String name;
private BigDecimal packetPrice;
...constructors, getters, setters...et
)
這是我用于@PutMapping 的類:
@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 類中的方法:
@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);
}
}
所以發生的事情是更改僅應用于 Packet 物體的第一個實體(id=1)。如何遍歷所有實體?
uj5u.com熱心網友回復:
您可以將此方法添加到您的存盤庫中,它將修改 Packets 表的所有條目:
@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);
}
uj5u.com熱心網友回復:
@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 變數中,您正在以新價格存盤資料包。在回圈之后,您將整個串列存盤在您的資料庫中的單個查詢中。這也將幫助您提高性能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468396.html
上一篇:抓取的內容與我在瀏覽器Inspector中看到的不同-PythonscraperwithSelenium
下一篇:命令結束時如何結束回圈
