我在Spring应用程序中遇到字段'id'没有默认值的错误。我尝试使用@Post方法创建一个申请人,但在创建申请人时,需要创建新的creditRating对象。
方法如下
public Applicant create(ApplicantDTO applicantDTO) {
Applicant applicant = ApplicantMapper.toEntity(applicantDTO);
applicant.setCreditRating(creditRatingService.create());
return applicantRepository.save(applicant);
}
这是我的申请人类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "applicant")
public class Applicant {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long identificationNumber;
private String firstName;
private String lastName;
private double monthlyIncome;
private String phoneNumber;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "credit_rating_id", referencedColumnName = "id")
private CreditRating creditRating;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "applicant_credit",
joinColumns = {@JoinColumn(name = "applicant_id")},
inverseJoinColumns = {@JoinColumn(name = "credit_id")}
)
private Credit credit;
}
这是CreditRating对象的创建方法。
public CreditRating create() {
CreditRating creditRating = new CreditRating();
creditRating.setCreditRating(getRandomCreditRating());
return creditRatingRepository.save(creditRating);
}
我希望在创建一个申请人时创建这个对象,但是不知何故,我认为JPA不能为它生成id,因为我是这样做的。
此处为信用评级实体
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "credit_rating")
public class CreditRating {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int creditRating;
}
1条答案
按热度按时间0mkxixxg1#
我发现了这个问题。问题出在数据库creditRating中,credit不知怎么没有勾选自动增量。我删除了模式,然后让JPA再次创建表。然后自动增量在credit和creditRating表上都被勾选了。