簡體   English   中英

JPA 沒有為實體生成 Id

[英]JPA not generating Id for entity

我有以下 class

  @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,並且嘗試將 object 插入到我的數據庫中時出現錯誤,ID 為 null。

@GeneratedValue(strategy = GenerationType.IDENTITY)

您正在使用GenerationType.IDENTITY這意味着IdentityGenerator期望由數據庫中的標識列生成的值,這意味着它們是自動遞增的。 使主鍵在數據庫中自動遞增以解決此問題。

或者您可以使用默認策略GenerationType.AUTO 在提交期間,AUTO 策略使用全局數字生成器為每個新實體 object 生成一個主鍵。 這些生成的值在數據庫級別是唯一的,並且永遠不會被回收。

@Id
@GeneratedValue
@Column(name = "comment_id")
private Long commentId;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM