简体   繁体   English

JPA 没有为实体生成 Id

[英]JPA not generating Id for entity

I have the following class我有以下 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());
    }

I get a CommentDto from my HTTP-Request consisting of a the text and the creatorId.我从我的 HTTP 请求中获得了一个 CommentDto,其中包含文本和 creatorId。

As far as I understand, the commentId should be generated through the call of the empty constructor.据我了解,commentId 应该是通过调用空构造函数生成的。

In my Service I do the following在我的服务中,我执行以下操作

public void addComment(CommentDto comment) {
  Comment commentEntity = new Comment(comment);
  commentRepository.save(commentEntity);
}

With commentRepository being an Autowired JPARepository<Comment, Long>使用commentRepository是自动装配的JPARepository<Comment, Long>

The problem is, that the ID does not get generated and I get an error for trying to insert an object into my DB with a null id.问题是,没有生成 ID,并且尝试将 object 插入到我的数据库中时出现错误,ID 为 null。

@GeneratedValue(strategy = GenerationType.IDENTITY)

You are using GenerationType.IDENTITY that means IdentityGenerator which expects values generated by an identity column in the database, meaning they are auto-incremented.您正在使用GenerationType.IDENTITY这意味着IdentityGenerator期望由数据库中的标识列生成的值,这意味着它们是自动递增的。 Make the primary key auto-incremented in database to solve this.使主键在数据库中自动递增以解决此问题。

Or you can use GenerationType.AUTO which is the default strategy.或者您可以使用默认策略GenerationType.AUTO During a commit, the AUTO strategy uses the global number generator to generate a primary key for every new entity object.在提交期间,AUTO 策略使用全局数字生成器为每个新实体 object 生成一个主键。 These generated values are unique at the database level and are never recycled.这些生成的值在数据库级别是唯一的,并且永远不会被回收。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM