sav*_*sav 1 java jpa spring-data-jpa
我有以下课程
@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());
}
Run Code Online (Sandbox Code Playgroud)
我从 HTTP 请求中获得一个 CommentDto,其中包含文本和 CreatorId。
据我了解,commentId 应该通过调用空构造函数来生成。
在我的服务中,我执行以下操作
public void addComment(CommentDto comment) {
Comment commentEntity = new Comment(comment);
commentRepository.save(commentEntity);
}
Run Code Online (Sandbox Code Playgroud)
作为commentRepositoryAutowiredJPARepository<Comment, Long>
问题是,ID 没有生成,并且我在尝试使用 null id 将对象插入数据库时收到错误。
@GeneratedValue(strategy = GenerationType.IDENTITY)
Run Code Online (Sandbox Code Playgroud)
您正在使用GenerationType.IDENTITY这意味着IdentityGenerator期望由数据库中的标识列生成的值,这意味着它们是自动递增的。使数据库中的主键自增即可解决此问题。
或者您可以使用GenerationType.AUTO默认策略。在提交期间,AUTO 策略使用全局编号生成器为每个新实体对象生成主键。这些生成的值在数据库级别是唯一的,并且永远不会被回收。
@Id
@GeneratedValue
@Column(name = "comment_id")
private Long commentId;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6025 次 |
| 最近记录: |