【发布时间】:2019-11-23 21:13:57
【问题描述】:
我编写了一个接收请求并将数据保存在数据库中的休息控制器。 这是我尝试使用邮递员发送的发帖请求。
{
"product_id" : "testproduct",
"default_concurrent":10,
"default_connections":1000,
"msan":10
}
我的实体类:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name="products")
@EntityListeners(AuditingEntityListener.class)
public class Product {
@Id
@Column(name="product_id", nullable = false)
private String product_id;
@Column(name="default_concurrent", nullable = true)
private int default_concurrent;
@Column(name="default_connections", nullable = true)
private int default_connections;
@Column(name="msan", nullable = true)
private int msan;
public String getProduct() {
return product_id;
}
public void setProduct(String product) {
this.product_id = product;
}
public int getDefault_concurrent() {
return default_concurrent;
}
public void setDefault_concurrent(int default_concurrent) {
this.default_concurrent = default_concurrent;
}
public int getDefault_connections() {
return default_connections;
}
public void setDefault_connections(int default_connections) {
this.default_connections = default_connections;
}
public int getMsan() {
return msan;
}
public void setMsan(int msan) {
this.msan = msan;
}
}
我的控制器:
@PostMapping("/add")
public Product addProduct(@Valid @RequestBody Product product)
{
return productDao.saveProduct(product);
}
错误:
ids for this class must be manually assigned before calling save()
nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.test.model.Product",
我在SO上浏览了很多与此错误相关的帖子,其中大多数建议使用
@GeneratedValue(strategy=GenerationType.AUTO) 或 @GeneratedValue(strategy=GenerationType.IDENTITY)
但我不能使用它,因为我的主键将是字符串,我不能将其更改为 Long。
在调试时,我可以看到在请求正文中我收到的 product_id 为 null。其余属性的值正确。
但是,如果我在数据库中再创建一列作为“Id”并相应地更新实体类,使“Id”作为主键并尝试执行,那么我在请求正文中得到正确的值,并且它被保存在数据库也是如此。
需要帮助。
【问题讨论】:
-
if 应该是模型中的 getProduct_id 和 setProduct_id。但更好的是你应该在 java 中改为驼峰式
-
如果变量名使用
_,请尝试使用@JsonProperty
标签: java hibernate rest spring-boot jpa-2.0