【发布时间】:2023-03-12 23:52:01
【问题描述】:
我正在从事一个练习 Spring Boot 项目,该项目从 mysql 数据库中列出/添加/更新/删除数学问题。我正在使用带有 JPA 的 Spring Boot 来执行数据库操作。就我而言,数据库已经存在问题,并且按钮“listproblems”将所有按钮返回到表中。我可以毫无问题地编辑/删除。但是当涉及到添加新问题时,我不知道如何将新条目添加到数据库中。在这一点上,我不知道要分享什么,但这里是当前的 addProblem 方法:
//This is in the ProblemController.java on the server side application
@PostMapping("/post")
public void addProduct(@RequestParam("cont") String pcont) {
// Get a valid pid first
Iterable<Problem> problist = probRepository.findAll();
int min = 100000;
int max = 0;
int gap = 0;
for (Problem myprod : problist) {
if (myprod.getPid() < min) {
min = myprod.getPid();
}
if (myprod.getPid() > max) {
max = myprod.getPid();
}
}
for (int i = min + 1; i < max; i++) {
if (!probRepository.existsById(i)) {
gap = i;
break;
}
}
if (gap == 0) {
gap = max + 1;
}
System.out.println("max: " + max);
max = max + 1;
Problem prob = new Problem();
prob.setPid(max);
prob.setContent(pcont);
probRepository.save(prob);
}
Problem.java 实体类
@Entity
public class Problem {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer pid;
@Column(name = "content")
private String content;
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
这个函数基本上是遍历项目以找到最大索引,然后将索引增加 1 以获得下一个索引。但它仍然不起作用。
如果您想看任何特别有助于我理解这一点的内容,请告诉我。
【问题讨论】:
标签: java mysql spring-boot maven jpa