java - JPA 没有为实体生成 ID
问题描述
我有以下课程
@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 的对象插入我的数据库时出现错误。
解决方案
@GeneratedValue(strategy = GenerationType.IDENTITY)
您正在使用GenerationType.IDENTITY
这种方法IdentityGenerator
,它期望由数据库中的标识列生成的值,这意味着它们是自动递增的。使主键在数据库中自动递增以解决此问题。
或者您可以使用GenerationType.AUTO
默认策略。在提交期间,AUTO 策略使用全局数字生成器为每个新实体对象生成一个主键。这些生成的值在数据库级别是唯一的,并且永远不会被回收。
@Id
@GeneratedValue
@Column(name = "comment_id")
private Long commentId;
推荐阅读
- python - 如何通过python中的迭代逐步减少y轴的差异来尽可能匹配两个不同的图
- powershell - Microsoft Power BI 中的自定义数据刷新
- python - 安全复制 (scp) 到达给定文件夹的最新文件?
- outlook-addin - Outlook“附加调试器”不可用
- google-chrome - 有没有办法在 Chrome 或 Firefox 中模拟低 dpi 渲染
- angular - 使用角度在本地保存当前主题值
- laravel - 如何将答案存储到数据库中
- visual-studio - 使用 MSDeploy 到远程服务器时,AjaxMin 未在 CopyAllFilesToSingleFolderForPackage 上运行
- python - python中的日志记录混乱
- dialog - 代号一 - 自定义对话框样式不起作用