【发布时间】:2022-11-24 05:23:44
【问题描述】:
我试图将一个对象保存到数据库,其中对象的 ID 是自动生成的。问题是由于某种原因 ID 仍然为 null(我也尝试在构造函数中硬编码一个 id,但它仍然被视为 null)。我测试了将一个对象插入到运行 sql 查询的数据库中,我可以在表中看到该条目。模型类是:`
package com.dealFinder.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
@ToString
@Entity
@Table(name = "deals")
public class DealModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotBlank(message = "Title is mandatory")
private String title;
@NotBlank(message = "Url is mandatory")
private String url;
private float price;
public DealModel(String title, String url, float price){
// this.id = 1;
this.title=title;
this.url = url;
this.price= price;
}
public DealModel(){}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "url", nullable = false)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Column(name = "price", nullable = false)
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
我用`创建对象
model = new DealModel(title, productUrl, price);
where title, productUrl and price are not null, and I persist it to the DB with
dealsRepository.save(dealModel);
where the dealRepository class is
@Repository
public interface DealsRepository extends JpaRepository<DealModel, Integer> {
}
` 不确定我最近做了什么错误的更改,因为它以前运行良好。
我正在尝试将 delModel 对象保存到数据库。运行手动查询以将 dealModel 条目插入表中工作正常
【问题讨论】:
-
为什么你有属性和吸气剂的映射?你必须选择一个
-
int是一个原语,默认为0..改为Integer。 -
显示包含“deals Repository.save(deal Model);”的类。你有没有注入你的依赖?
-
@SimonMartinelli 我尝试将映射仅保留在属性和吸气剂上,但它仍然不起作用。 ID 将始终为 null M.Deinum 我将 Id 类型设为 Integer,但它仍然无济于事
-
我用您的代码创建了一个示例项目,一切正常。查看github.com/simasch-scratches/so-74530613
标签: java spring spring-boot spring-data-jpa