我有以下课程
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "comment_id")
private Long commentId;
@Column(name = "creator_id")
private Long creatorId;
@Column(name = "text")
@ApiModelProperty(value = "Text des Kommentar")
private String text;
@Column(name = "timestamp")
@ApiModelProperty(value = "Zeitstempel der letzten Bearbeitung")
private String timestamp;
protected Comment() {}
public Comment(CommentDto dto) {
this();
updateComment(dto);
}
private void updateComment(CommentDto dto) {
setText(dto.getText());
setCreatorId(dto.getCreatorId());
setTimestamp(UtilService.getTimestampString());
}
我从HTTP请求中获得一个CommentDto,其中包含文本和creatorId。
据我了解,commentId应该通过空构造函数的调用生成。
在我的服务中,我执行以下操作
public void addComment(CommentDto comment) {
Comment commentEntity = new Comment(comment);
commentRepository.save(commentEntity);
}
commentRepository
是自动连接的JPARepository<Comment, Long>
问题是,没有生成ID,并且在尝试将具有空ID的对象插入数据库时出现错误。
答案 0 :(得分:2)
@GeneratedValue(strategy = GenerationType.IDENTITY)
您使用的GenerationType.IDENTITY
表示IdentityGenerator
期望由数据库中的Identity列生成的值,意味着它们是自动递增的。 使数据库中的主键自动递增以解决此问题。
或者您可以使用GenerationType.AUTO
这是默认策略。在提交期间,AUTO策略使用全局数字生成器为每个新实体对象生成一个主键。这些生成的值在数据库级别是唯一的,并且永不回收。
@Id
@GeneratedValue
@Column(name = "comment_id")
private Long commentId;