java通过自动增量创建jsonobject,以便在数据库中保存POST REQUEST
我使用springboot创建webservice并与我的angular项目连接 因此,我在Crudepository中使用save()来插入和更新,但当我在POSTMAN中使用JSON发送POST请求以插入新对象时,我得到一个错误:
"status": 500,
"error": "Internal Server Error",
"message": "could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet",
"path": "/update"
更新数据库中的现有id是可以的,但对于新id则失败
JSON示例
{ "id": 5, <------auto_increment
"name": "John", "description": "handsome" }
@RestController{
@Autowired
Connect connect;
@PostMapping("/update")
public Topic updateTopic(@RequestBody Topic topic){
connect.save(topic);
return topic;
}
}
>
@Entity
@Table(name = "info")
public class Topic implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
@JsonView(View.Summary.class)
private String name;
@Column(name = "description")
@JsonView(View.Summary.class)
private String description;
public Topic (){
}
public Topic(String name,String description){
this.name = name;
this.description = description;
}
public Topic(Long id,String name,String description){
this.id = id;
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
如何编写json以匹配Autoincrement并插入新id
# 1 楼答案
我已经解决了这个问题,我只是改变了
到
# 2 楼答案
您根本不需要为JSON中的新实体生成ID
参见^{} 的javadoc:
持久化给定的瞬态实例,首先分配一个生成的标识符。(如果使用了分配的生成器,则使用标识符属性的当前值。)
因此,简单地说,您应该生成没有ID的新实体JSON,并让Hibernate为新实体生成新ID。这样,新ID将遵循您为此实体选择的ID生成策略(在您的案例中
@GeneratedValue(strategy = GenerationType.AUTO)
)