如何激活列表中的单行?
Posted
技术标签:
【中文标题】如何激活列表中的单行?【英文标题】:How do I activate a single row from a list? 【发布时间】:2021-12-02 00:23:18 【问题描述】:我有一个实体投资列表显示,其中包含来自数据库的五行,状态最初设置为待处理。我想要做的是在每个结果行中添加一个激活功能按钮(React),这样当在一行上单击激活按钮时,它将获取投资 ID 并执行激活功能并将状态更改为 "Active" 。我正在发送 POST 请求,但在获取行 ID 时遇到问题。我可能做错了什么?
这是投资实体
public class Investment
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//@Column(nullable = true)
@ManyToOne(targetEntity = com.bethsaida.org.models.Customer.class,
cascade = CascadeType.ALL, fetch = FetchType.LAZY )
@JoinColumn(name="customer_id")
private Customer customer ;
@Column(name = "AccountNumber", updatable = false, nullable = false)
private int accountNumber;
private String category;
private BigDecimal principal;
//private BigDecimal netInvestmentAmount;
private BigDecimal currentInterest;
private BigDecimal maturityInterest;
private String tenure;
private String marketer;
private String investmentPackage;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate startDate;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate maturityDate;
private int rate;
这是实现激活逻辑的服务类
public void activateInvestment(Investment investment, Long id)
if(!(investment.getRate() <= 0))
investment.setStatus(InvestmentStatus.Active);
else
System.out.println("Investment Rate Can't be Null");
这是 Controller 类
@PostMapping(value="/activateInvestment/id")
public void activateInvestment(@RequestBody Investment investment, @PathVariable Long id)
investmentService.activateInvestment(investment, id);
【问题讨论】:
【参考方案1】:您的@PathVariable Long id 没有做任何事情,为什么在它没有做任何事情的情况下包含在请求中?
通常建议您使用映射到实体对象的 DTO 对象。我不确定,但我认为当您在请求中收到投资对象时,它不会自动持久化。这意味着您不能只更改对象的值并希望在数据库中更改它。
请看以下内容。
https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
我建议你这样做:
public void activateInvestment(InvestmentDTO investmentDto, Long id)
if(!(investmentDto.getRate() <= 0))
Investment investment = getInvestmentFromId(id);
investment.setStatus(InvestmentStatus.Active);
investment.setRate(investmentDto.getRate());
investmentRepository.save(investment); //If not in a transaction
else
throw new RuntimeException("Investment Rate Can't be Null");
private Investment getInvestmentFromId(Long id)
return investmentRepository.getFromId(id);
你的控制器类是:
@PostMapping(value="/activateInvestment/id")
public void activateInvestment(@RequestBody InvestmentDTO investmentDto, @PathVariable Long id)
investmentService.activateInvestment(investmentDto, id);
【讨论】:
以上是关于如何激活列表中的单行?的主要内容,如果未能解决你的问题,请参考以下文章